package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.ResTransaction;
import com.xmy.cultivate.enums.*;
import com.xmy.cultivate.excel.ReturnPremiumDailySheet;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.respons.OrderApplyMoreRs;
import com.xmy.cultivate.respons.ResStudentAccount;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单报名信息 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-07-28
 */
@Service
public class OrderApplyServiceImpl extends ServiceImpl<OrderApplyMapper, OrderApply> implements IOrderApplyService {

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    ICoursePricingService iCoursePricingService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IOrderTransferService iOrderTransferService;

    @Autowired
    @Lazy
    IOrderTransferDetailService iOrderTransferDetailService;

    @Autowired
    @Lazy
    IOrderPayAccountService iOrderPayAccountService;

    @Autowired
    @Lazy
    OrderApplyMapper orderApplyMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IRenewClassService iRenewClassService;

    @Autowired
    @Lazy
    IOrderCoursePricingService iOrderCoursePricingService;

    @Autowired
    @Lazy
    IStudentTypeService iStudentTypeService;

    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
    @Lazy
    IRenewDataService iRenewDataService;

    @Autowired
    @Lazy
    CompanyMapper companyMapper;

    @Autowired
    @Lazy
    SubjectsMapper subjectsMapper;

    @Autowired
    @Lazy
    IStudentSchoolService iStudentSchoolService;

    @Autowired
    @Lazy
    EnrollInfoMapper enrollInfoMapper;

    @Autowired
    @Lazy
    IEnrollTeamMemberService iEnrollTeamMemberService;

    @Autowired
    @Lazy
    IRatePayService iRatePayService;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    IRecordCostService iRecordCostService;

    @Autowired
    @Lazy
    IDealInfoService iDealInfoService;

    @Autowired
    @Lazy
    IStudentFaceDataService iStudentFaceDataService;

    @Autowired
    @Lazy
    IStudentAccountService iStudentAccountService;

    @Autowired
    @Lazy
    IDictService iDictService;

    @Autowired
    @Lazy
    IOrderDisDetailService iOrderDisDetailService;

    @Autowired
    @Lazy
    IOrderApplyAffirmService iOrderApplyAffirmService;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    @Lazy
    IStaffService iStaffService;

    @Autowired
    @Lazy
    IOrderDisPriceService iOrderDisPriceService;

    @Autowired
    @Lazy
    IOrderDisClanService iOrderDisClanService;

    @Autowired
    @Lazy
    IRadeExcludeStudentService iRadeExcludeStudentService;

    @Autowired
    @Lazy
    RadeExcludeStudentMapper radeExcludeStudentMapper;

    @Autowired
    @Lazy
    ICourseSchedulingAlwaysService iCourseSchedulingAlwaysService;

    @Autowired
    @Lazy
    ICisPositionService iCisPositionService;

    @Autowired
    @Lazy
    IStudentClassTypeService iStudentClassTypeService;

    @Autowired
    @Lazy
    IEnrollSetService iEnrollSetService;

    @Autowired
    @Lazy
    IEnrollCustomerService iEnrollCustomerService;

    @Autowired
    @Lazy
    ILackCourseLogService iLackCourseLogService;

    @Autowired
    @Lazy
    IEnrollInfoGrantSchoolService iEnrollInfoGrantSchoolService;

    @Autowired
    IStudentNewsService iStudentNewsService;

    @Autowired
    IOrderReturnTeacherService iOrderReturnTeacherService;

    @Autowired
    IOrderReturnCauseService iOrderReturnCauseService;

    @Autowired
    ICommonCauseService iCommonCauseService;

    @Autowired
    IWecharsBindService iWecharsBindService;

    @Autowired
    ILklOrderService iLklOrderService;

    /**
     * 订单类型：1报名，2补费，3转课，4退费,5转校
     *
     * @param orderApply
     * @return
     */
    @Transactional
    public boolean saveTo(OrderApply orderApply) throws ParseException {
        Integer orderType = orderApply.getOrderType().getKey();
        Long subjectsId = 0L;
        Long studentId = 0L;
        Long applyCount = 0L;

        if (orderType == Code.ORDER_TYPE_SiGN) {
            for (OrderDetail orderDetail : orderApply.getOrderDetailList()) {
                subjectsId = orderDetail.getSubjectsId();
                studentId = orderApply.getStudentId();

                Course course = iCourseService.getById(orderDetail.getCourseId());
                iRadeExcludeStudentService.isNewStudent(course.getYearClassId().getKey(), subjectsId, studentId, orderDetail.getSchoolId());
            }
            applyCount = this.getApplyCount(subjectsId.toString(), studentId.toString());
        } else {
            if (orderApply.getOrderDetailList() != null && orderApply.getOrderDetailList().size() > 0) {
                for (OrderDetail orderDetail : orderApply.getOrderDetailList()) {
                    subjectsId = orderDetail.getSubjectsId();
                    studentId = orderApply.getStudentId();
                }
            }
        }

        OrderTransfer orderTransfer = orderApply.getOrderTransfer();
        //转课
        if (orderType == Code.ORDER_TYPE_TRANSFER) {
            if (orderTransfer.getOutSchoolId().equals(orderTransfer.getInSchoolId()) == false) {
                throw new CommonException(ResultCode.SCHOOL_IN_EQUAL);
            }
        }

        orderApply.setSchoolId(orderApply.getHandleSchoolId());//所属校区
        //添加所属校区
        iStudentSchoolService.addOrUpdateData(orderApply.getStudentId(), orderApply.getHandleSchoolId());

        //修改学生所属校区
        Student student = iStudentService.getById(orderApply.getStudentId());
        if (student != null) {
            if (!student.getSchoolId().equals(orderApply.getHandleSchoolId())) {
                student.setSchoolId(orderApply.getHandleSchoolId());
                iStudentService.updateById(student);
            }
        }
        if (orderApply.getDisPrice() != null && orderApply.getDisPrice().compareTo(new BigDecimal(0)) > 0) {
            orderApply.setDiscountsDate(LocalDate.now());
        }
        if (orderApply.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_REFUND)) {
            orderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_REFUND);
        }
        orderApplyMapper.insert(orderApply);

        //补费，转课，退费信息，防止重复提交（备注：待完成）
        if (orderType == Code.ORDER_TYPE_SUPP || orderType == Code.ORDER_TYPE_TRANSFER || orderType == Code.ORDER_TYPE_REFUND) {

        }

        //****************************************补费，转课，退费信息 start***********************************//
        //转课
        if (orderType == Code.ORDER_TYPE_TRANSFER && orderTransfer != null) {
            //orderApply.setOrderType(orderType);
            orderApply.setTransferPrice(orderTransfer.getOutPrice());//转出抵扣金额
        }
        //****************************************补费，转课，退费信息 end***********************************//

        //订单类型,1报名，2补费，3转课，4退费
        if (orderType == Code.ORDER_TYPE_SiGN) {
            if (orderApply.getOwnPrice() != null) {
                if (orderApply.getOwnPrice().compareTo(BigDecimal.ZERO) > 0) {
                    orderApply.setIsOwn(1);//设置为欠费状态
                }
            }
        }

        String tradeContent = "";//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元
        Long outSubjectsId = 0L;//转出课程
        Long inSubjectsId = 0L;//转入课程
        if (orderType == Code.ORDER_TYPE_TRANSFER) {
            //转课
            Course inCourse = iCourseService.getById(orderTransfer.getInGradeId());
            inSubjectsId = inCourse.getSubjectsId();
        }

        //2补费，3转课，4退费
        if ((orderType == Code.ORDER_TYPE_TRANSFER || orderType == Code.ORDER_TYPE_SUPP || orderType == Code.ORDER_TYPE_REFUND || orderType == Code.ORDER_TYPE_TRANSFERSCHOOL) && orderTransfer != null) {
            orderTransfer.setOrderId(orderApply.getId());
            iOrderTransferService.save(orderTransfer);
            Course outCourse = iCourseService.getById(orderTransfer.getOutGradeId());
            outSubjectsId = outCourse.getSubjectsId();
            if (orderType == Code.ORDER_TYPE_TRANSFER) {
                tradeContent += "转出：" + outCourse.getName() + "," + orderTransfer.getOutHouse() + "课次," + orderTransfer.getOutPrice() + "元";
            } else if (orderType == Code.ORDER_TYPE_SUPP) {
                //tradeContent += "补费："+orderTransfer.getOutPrice()+"元";

            } else if (orderType == Code.ORDER_TYPE_REFUND) {
                tradeContent += "退费：" + outCourse.getName() + "退" + orderTransfer.getOutHouse() + "课次，应退学费" + orderTransfer.getOutPrice() + "元";
            }
        }


        //System.out.print("insertId:"+orderApply.getId());
        //分班
        List<StudentGrade> studentGradeList = new ArrayList<>();
        //续费信息
        List<RenewClass> renewClassesList = new ArrayList<>();

        //报名与转课
        //*************************************订单详情start**************************************************//

        Integer allApplyCourseCount = 0;//总共报读多少科
        Integer yearPart = 0;
        Integer quarterNum = 0;

        Integer yearClassId = null;
        Set<String> subjectsIdSet = new HashSet<>();


        if (orderType == Code.ORDER_TYPE_SiGN || orderType == Code.ORDER_TYPE_TRANSFER) {
            //支付详情
            List<OrderDetail> orderDetailList = new ArrayList<>();
            Iterator<OrderDetail> orderDetailIterator = orderApply.getOrderDetailList().iterator();
            while (orderDetailIterator.hasNext()) {

                if (orderType == Code.ORDER_TYPE_SiGN) {
                    if (tradeContent != "") {
                        tradeContent += "</br>";
                    } else {
                        tradeContent += "报名：";
                    }
                } else {
                    tradeContent += "</br>转入：";
                }

                OrderDetail orderDetail = orderDetailIterator.next();
                orderDetail.setHandleDate(orderApply.getHandleDate());
                orderDetail.setOrderType(orderApply.getOrderType());
                orderDetail.setId(idWorker.nextId());
                orderDetail.setStudentId(orderApply.getStudentId());
                orderDetail.setUseCourseCount(0);
                orderDetail.setAllCourseCount(orderDetail.getAllCourseCount());//总课时
                orderDetail.setResidueCourseCount(orderDetail.getAllCourseCount());//剩余课时
                orderDetail.setResiduePrice(orderDetail.getSolidPrice());//实收金额
                allApplyCourseCount = allApplyCourseCount + orderDetail.getAllCourseCount();
                //studentGrade.setSchoolId();
                //studentGrade.setEndDate();

                //studentGrade.setAllCourseCount(orderDetail.getAllCourseCount());
                //studentGrade.setUseCourseCount(0);
                //studentGrade.setResidueCourseCount(orderDetail.getAllCourseCount());
                Course course = iCourseService.getById(orderDetail.getCourseId());
                //添加当前报读的续班信息
                Integer year_part = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份
                orderApply.setLessonType(course.getLessonType());
                orderDetail.setLessonType(course.getLessonType());
                orderDetail.setCourseName(course.getName());
                orderDetail.setSubjectsId(course.getSubjectsId());
                subjectsId = course.getSubjectsId();//

                orderDetail.setYearPart(year_part);
                orderDetail.setYearClassId(course.getYearClassId().getKey());
                yearClassId = course.getYearClassId().getKey();
                subjectsIdSet.add(course.getSubjectsId().toString());

                //设置报读的季度
                orderDetail.setQuarterNum(course.getQuarterNum());

                yearPart = year_part;
                quarterNum = course.getQuarterNum();
                //年份与季度
                orderDetail.setYearAndQuarter(Integer.parseInt(year_part + "" + course.getQuarterNum()));

                Integer yearPartAndQuarter = orderDetail.getYearAndQuarter();

                tradeContent += course.getName() + ",";

                //续班信息
                /*RenewClass renewClass = iQuarterService.getRenewForPay(orderApply.getStudentId(),orderDetail.getSchoolId(),orderDetail.getSubjectsId(),orderDetail.getCourseId(),orderDetail.getAllCourseCount(),orderType);
                renewClass.setOrderType(orderApply.getOrderType().getKey());
                if(renewClass.getReSetIsnew() == 1){
                    orderDetail.setIsNewStudent(1);//设置为新生
                }else {
                    orderDetail.setIsNewStudent(0);
                }*/

                Grade grade = null;
                if (orderDetail.getGradeId() != null) {
                    //分班
                    /*StudentGrade studentGrade = new StudentGrade();
                    studentGrade.setOrderDetailId(orderDetail.getId());
                    studentGrade.setStudentId(orderApply.getStudentId());
                    studentGrade.setSubjectsId(course.getSubjectsId());//科目id
                    studentGrade.setGradeId(orderDetail.getGradeId());
                    studentGrade.setCourseId(orderDetail.getCourseId());
                    studentGrade.setYearPart(year_part);
                    studentGrade.setQuarterNum(course.getQuarterNum());
                    studentGrade.setYearClassId(course.getYearClassId().getKey());*/

                    //studentGrade.setOrderDetailId(orderDetail.getId());//设置订单id
                    grade = iGradeService.getById(orderDetail.getGradeId());
                    if (grade != null) {
                        orderDetail.setGradeName(grade.getName());
                        orderDetail.setCourseHouse(grade.getStuDeductHour());
                        //studentGrade.setSchoolId(grade.getSchoolId());
                        //orderDetail.setSchoolId(grade.getSchoolId());
                        tradeContent += grade.getName() + ",";

                        //添加到班级
                        Long studentGradeId = iStudentGradeService.addData(orderDetail.getId(), grade.getSchoolId(), orderApply.getStudentId(), grade.getId(), course.getId(), course.getSubjectsId(), year_part, course.getQuarterNum(), orderDetail.getAllCourseCount(), course.getYearClassId().getKey(), grade.getLessonType(), grade.getCourseTypeId(), 1);
                        //iStudentGradeService.updateIsLast(grade.getYearPart(), course.getQuarterNum(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), grade.getLessonType());
                        //设置续班老师
                        /*if(orderType == Code.ORDER_TYPE_SiGN){
                            studentGrade.setRenewTeacherId(grade.getTeacherId());
                        }else {
                            //转课
                            if(orderDetail.getAllCourseCount()>3){
                                studentGrade.setRenewTeacherId(grade.getTeacherId());
                            }
                        }*/

                    }
                    //studentGradeList.add(studentGrade);
                } else {
                    //0为新生
                    Long count = this.getApplyCountForIsNew(subjectsId.toString(), studentId.toString());
                    if (count.equals(0L)) {
                        //新生自动分班
                        iStudentGradeService.addNewStudentGrade(orderDetail.getId(), orderApply.getHandleSchoolId(), year_part, course.getQuarterNum(), orderApply.getStudentId(), course.getSubjectsId(), course.getYearClassId().getKey(), course.getId(), orderDetail.getAllCourseCount(), course.getLessonType());
                    } else {
                        iStudentGradeService.notDataAndAddData(orderDetail.getId(), orderApply.getHandleSchoolId(), orderApply.getStudentId(), course.getId(), course.getSubjectsId(), year_part, course.getQuarterNum(), orderDetail.getAllCourseCount(), course.getYearClassId().getKey(), course.getLessonType());
                    }
                }

                tradeContent += orderDetail.getPrice();

                if (orderDetail.getCoursePriceId() != null) {
                    CoursePricing coursePricing = iCoursePricingService.getById(orderDetail.getCoursePriceId());
                    if (coursePricing != null) {
                        tradeContent += "(" + coursePricing.getCountUnit() + ")*" + orderDetail.getCount() + "=" + orderDetail.getSolidPrice() + "元";
                        orderDetail.setCoursePriceName(coursePricing.getCount() + coursePricing.getCountUnit() + "=" + coursePricing.getAllPrice() + "元");

                        //保存到订单支付价格表
                        OrderCoursePricing orderCoursePricing = new OrderCoursePricing();

                        orderCoursePricing.setId(orderDetail.getId());
                        orderCoursePricing.setPrice(coursePricing.getPrice());
                        orderCoursePricing.setCount(coursePricing.getCount());
                        orderCoursePricing.setCountUnit(coursePricing.getCountUnit());
                        orderCoursePricing.setUnitPrice(coursePricing.getUnitPrice());
                        orderCoursePricing.setChargeMode(coursePricing.getChargeMode());
                        orderCoursePricing.setServePrice(coursePricing.getServePrice());
                        orderCoursePricing.setMaterialsPrice(coursePricing.getMaterialsPrice());
                        orderCoursePricing.setAllPrice(coursePricing.getAllPrice());
                        iOrderCoursePricingService.saveOrUpdate(orderCoursePricing);
                    }
                }
                orderDetail.setOrderId(orderApply.getId());

                if (orderDetail.getDiscountsPrice() != null && orderDetail.getDiscountsPrice().compareTo(new BigDecimal(0)) > 0) {
                    orderDetail.setDiscountsDate(LocalDate.now());
                    List<OrderDisDetail> orderDisDetailList = orderDetail.getOrderDisDetailList();
                    /*if (orderDisDetailList != null) {
                        for (OrderDisDetail orderDisDetail : orderDisDetailList) {
                            orderDisDetail.setOrderId(orderApply.getId());
                            orderDisDetail.setDisReasonName(iDictService.getDictNameForNum(orderDisDetail.getDisReasonId(), 24));
                            iOrderDisDetailService.save(orderDisDetail);
                        }
                    }*/
                    Long disOrderId = orderApply.getId();
                    // 直系亲属保存
                    iOrderDisDetailService.addDisDetailAndClan(orderApply.getStudentList(), orderDetail.getId(), orderApply.getId(), disOrderId, orderDisDetailList, orderDetail.getDiscountsPrice(), LocalDate.now());
//                    iOrderDisDetailService.addDisDetaill(orderApply.getId(), disOrderId, orderDisDetailList, orderDetail.getDiscountsPrice(), LocalDate.now());

                }

                //renewClass.setOrderDetailId(orderDetail.getId());
                //renewClassesList.add(renewClass);
                //orderDetail.setYearPart(renewClass.getYearPart());
                iOrderDetailService.save(orderDetail);
                //orderDetailList.add(orderDetail);

                // 缴费成功，同步到mq原本算教学主管的数据变更为当前带班老师
                iMqPushService.leaveTeacherStudentByPay(orderDetail);

                //设置为新生或者老生
                Company company = companyMapper.selectById(1L);
                if (company.getIsUseNewOld() == 1) {
                    iStudentTypeService.addData(orderDetail.getSchoolId(), orderDetail.getStudentId(), course.getSubjectsId(), orderDetail.getIsNewStudent());
                } else {
                    iStudentTypeService.addData(orderDetail.getSchoolId(), orderDetail.getStudentId(), course.getSubjectsId(), 1);
                }
                //更新续班信息是否成功
                if (orderType == Code.ORDER_TYPE_SiGN) {
                    //报名
                    //iRenewDataService.updateData(orderDetail.getSchoolId(), orderDetail.getStudentId(), course, grade, orderDetail.getAllCourseCount(), 1, orderDetail.getId());

                    /**
                     * 缴费率数据
                     */
                    try {
                        StudentGrade studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getYearPart(), orderDetail.getQuarterNum(), course.getLessonType());
                        Grade gradeOld = null;
                        if (studentGrade != null) {
                            gradeOld = iGradeService.getById(studentGrade.getGradeId());
                        }
                        if (gradeOld != null) {
                            RatePay ratePay = new RatePay();
                            ratePay.setSchoolId(orderApply.getSchoolId());
                            ratePay.setTeacherId(gradeOld.getTeacherId());
                            ratePay.setStudentId(orderDetail.getStudentId());
                            ratePay.setSubjectsId(orderDetail.getSubjectsId());
                            ratePay.setGradeId(gradeOld.getId());
                            ratePay.setYearPart(orderDetail.getYearPart());
                            ratePay.setQuarterNum(orderDetail.getQuarterNum());
                            ratePay.setYearClassId(orderDetail.getYearClassId());
                            ratePay.setOrderId(orderDetail.getOrderId());
                            ratePay.setOrderDetailId(orderDetail.getId());
                            ratePay.setId(idWorker.nextId());
                            ratePay.setNum(1);
                            ratePay.setAddDate(LocalDate.now());
                            ratePay.setCreatedAt(LocalDateTime.now().withNano(0));
                            if (orderApply.getSignType().equals(3)) {
                                ratePay.setStatus(2);//如果是lkl创建订单，这里先设置为2，支付成功后，再用回调方法调整为1
                            }
                            if (orderDetail.getResidueCourseCount() >= 45) {
                                Integer rayNum = orderDetail.getResidueCourseCount() / 45;
                                ratePay.setNum(rayNum);
                                iRatePayService.save(ratePay);
                            } else {
                                Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), yearPartAndQuarter, course.getLessonType());
                                if (residueCourseCount >= 45) {
                                    Integer rayNum = residueCourseCount / 45;
                                    ratePay.setNum(rayNum);
                                    iRatePayService.save(ratePay);
                                }
                            }
                        }
                    } catch (Exception e) {

                    }

                } else {
                    //转课
                    iRenewDataService.updateData(orderDetail.getSchoolId(), orderDetail.getStudentId(), course, grade, orderDetail.getAllCourseCount(), 2, orderDetail.getId());
                }

                iRenewDataService.addData(orderDetail.getSchoolId(), orderDetail.getStudentId(), year_part, course, grade);

                /**
                 * 续报信息
                 */
                if (orderType == Code.ORDER_TYPE_SiGN) {
                    if (applyCount > 0) {
                        if (orderApply.getDealList() != null) {
                            Integer dealListCount = orderApply.getDealList().size();
                            if (dealListCount > 0) {
                                Integer dealCount = (Integer) orderDetail.getAllCourseCount() / 45;
                                BigDecimal dealNum = new BigDecimal(dealCount).divide(new BigDecimal(dealListCount), 2, RoundingMode.HALF_UP);
                                for (Long id : orderApply.getDealList()) {
                                    DealInfo dealInfo = new DealInfo();
                                    //复制
                                    BeanUtils.copyProperties(orderDetail, dealInfo);
                                    Long dealInfoId = idWorker.nextId();
                                    dealInfo.setId(dealInfoId);
                                    //dealInfo.setId(idWorker.nextId());
                                    dealInfo.setCount(dealNum);
                                    dealInfo.setOrderId(orderApply.getId());
                                    dealInfo.setSchoolId(orderApply.getSchoolId());
                                    dealInfo.setSubjectsId(subjectsId);
                                    dealInfo.setTeacherId(id);
                                    dealInfo.setAddDate(LocalDate.now());
                                    iDealInfoService.save(dealInfo);
                                }
                            }
                        }
                    }
                }


                /**
                 * 添加智能课帐号,移动到了Controller里面了
                 */
                if (orderType == Code.ORDER_TYPE_SiGN) {
                    //if (orderDetail.getSubjectsId() == 1L && orderDetail.getGradeId() != null) {
                    //    iStudentAccountService.applyAddStudentAccount(orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getGradeId(), orderDetail.getCourseId());
                    //}
                    //iMqPushService.updateStudentAccount(orderDetail.getStudentId(),orderDetail.getSubjectsId());
                    /*if (orderDetail.getLessonType().equals(1)){
                        try {
                            String exchangeName = MqConstants.EXCHANGE_ERP_ADD_STUDENT_ACCOUNT_FANOUT;
                            rabbitTemplate.convertAndSend(exchangeName, null, orderDetail.getStudentId());
                        }catch (Exception e){

                        }
                    }*/
                }
                //智能课或者精品课
                try {
                    Integer lessonType = 1;
                    //iOrderDetailService.addOrderApply(yearPart, quarterNum, orderDetail.getSchoolId(), orderDetail.getSubjectsId(), lessonType, orderDetail.getStudentId());
                    //以下是异步，但是由于这里使用了事务，异步不能写在这里，故注释掉
                    //iMqPushService.autoOrderApply(yearPart, quarterNum, orderDetail.getSchoolId(), orderDetail.getSubjectsId(), lessonType, orderDetail.getStudentId());
                } catch (Exception e) {
                }
            }


            if (orderDetailList.size() > 0) {
                //为了添加交易内容，放在上面一条一条加
                //iOrderDetailService.saveBatch(orderDetailList,orderDetailList.size());
            }
            if (studentGradeList.size() > 0) {
                iStudentGradeService.saveBatch(studentGradeList, studentGradeList.size());
            }
        }

        //*************************************订单详情end**************************************************//

        //*************************************支付信息start**************************************************//
        List<OrderPayAccount> orderPayAccountList = new ArrayList<>();
        Iterator<OrderPayAccount> orderPayAccountIterator = orderApply.getOrderPayAccountList().iterator();
        while (orderPayAccountIterator.hasNext()) {
            OrderPayAccount orderPayAccount = orderPayAccountIterator.next();
            orderPayAccount.setOrderId(orderApply.getId());
            orderPayAccountList.add(orderPayAccount);
        }
        if (orderPayAccountList.size() > 0) {
            iOrderPayAccountService.saveBatch(orderPayAccountList, orderPayAccountList.size());
        }
        //*************************************支付信息end**************************************************//

        //****************************************补费start***********************************//
        if (orderType == Code.ORDER_TYPE_SUPP) {
            tradeContent += "补费：";
            List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();
            Iterator<OrderTransferDetail> orderTransferDetailIterator = orderApply.getOrderTransferDetailList().iterator();
            while (orderTransferDetailIterator.hasNext()) {
                OrderTransferDetail orderTransferDetail = orderTransferDetailIterator.next();
                orderTransferDetail.setOrderType(orderApply.getOrderType());
                orderTransferDetail.setOrderId(orderApply.getId());//设置对应的新订单id
                //补费
                if (orderType == Code.ORDER_TYPE_SUPP) {
                    UpdateWrapper<OrderApply> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", orderTransferDetail.getOldOrderId());
                    updateWrapper.set("is_own", 0);
                    orderApplyMapper.update(null, updateWrapper);

                    //交易内容
                    List<OrderDetail> orderDetailList = iOrderDetailService.list(new QueryWrapper<OrderDetail>().eq("order_id", orderTransferDetail.getOldOrderId()));
                    for (OrderDetail orderDetail : orderDetailList) {
                        tradeContent += orderDetail.getCourseName() + " ";
                        tradeContent += orderTransferDetail.getInPrice() + "元";
                    }
                }
                iOrderTransferDetailService.save(orderTransferDetail);
                //orderTransferDetailList.add(orderTransferDetail);
            }
        }
        //****************************************补费end***********************************//

        //****************************************转课start***********************************//


        if (orderType == Code.ORDER_TYPE_TRANSFER) {
            Long transferCourseId = null;
            Boolean isAll = true;//是否全部转出

            List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();
            Iterator<OrderTransferDetail> orderTransferDetailIterator = orderApply.getOrderTransferDetailList().iterator();
            while (orderTransferDetailIterator.hasNext()) {
                OrderTransferDetail orderTransferDetail = orderTransferDetailIterator.next();
                orderTransferDetail.setOrderType(orderApply.getOrderType());
                orderTransferDetail.setOrderId(orderApply.getId());//设置对应的新订单id
                //转课，扣除原有课时
                if (orderTransferDetail.getOutHouse() > 0) {
                    OrderDetail orderDetail = orderDetailMapper.selectById(orderTransferDetail.getOldOrderDetailId());
                    yearPart = orderDetail.getYearPart();
                    quarterNum = orderDetail.getQuarterNum();
                    subjectsId = orderDetail.getSubjectsId();
                    if (orderDetail != null) {
                        transferCourseId = orderDetail.getCourseId();
                        UpdateWrapper<OrderDetail> orderDetailUpdateWrapper = new UpdateWrapper<>();
                        Integer courseHouse = orderDetail.getResidueCourseCount() - orderTransferDetail.getOutHouse();
                        //转出课时不能大于剩余课时
                        if (courseHouse < 0) {
                            throw new CommonException(ResultCode.OUT_COURSE_BIG);
                        } else if (courseHouse == 0) {
                            orderDetailUpdateWrapper.set("reading_status", 2);//全部转出，把课程设置为转出状态

                            StudentGrade studentGrade = iStudentGradeService.getById(orderDetail.getId());
                            if (studentGrade != null) {
                                if (studentGrade.getUseCourseCount() == 0) {
                                    iStudentSchoolService.removeById(studentGrade);
                                } else {
                                    //把所在班级设置为结课状态
                                    UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                                    //studentGradeUpdateWrapper.set("status",2);
                                    studentGradeUpdateWrapper.set("reading_status", ReadingStatusEnum.FINISH.getKey());
                                    studentGradeUpdateWrapper.eq("order_detail_id", orderDetail.getId());
                                    iStudentGradeService.update(null, studentGradeUpdateWrapper);
                                }
                            }
                        } else if (courseHouse > 0) {
                            isAll = false;
                        }
                        //orderDetailUpdateWrapper.eq("id",orderDetail.getId());
                        //orderDetailUpdateWrapper.set("residue_course_count",courseHouse);
                        //orderDetailUpdateWrapper.set("residue_price",)
                        //orderDetailMapper.update(null,orderDetailUpdateWrapper);
                        orderDetail.setResidueCourseCount(courseHouse);//设置剩余课时
                        //设置剩余金额
                        BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                        residuePrice = residuePrice.subtract(orderTransferDetail.getOutPrice());
                        //返回0表示等于0，返回1表示大于0，返回-1表示小于0
                        if (residuePrice.compareTo(BigDecimal.ZERO) == -1) {

                        }
                        orderDetail.setResiduePrice(residuePrice);

                        //转出课时与金额
                        Integer outHouse = orderTransferDetail.getOutHouse();
                        BigDecimal outPrice = orderTransferDetail.getOutPrice();

                        orderDetail.setRollOutHouse(outHouse + orderDetail.getRollOutHouse());
                        orderDetail.setRollOutPrice(outPrice.add(orderDetail.getRollOutPrice()));
                        iOrderDetailService.updateById(orderDetail);
                        //orderDetail.setResiduePrice();
                        Course course = iCourseService.getById(orderDetail.getCourseId());
                        yearClassId = course.getYearClassId().getKey();
                        subjectsIdSet.add(course.getSubjectsId().toString());
                    } else {
                        throw new CommonException(ResultCode.OUT_COURSE_NOT);
                    }
                }
                iOrderTransferDetailService.save(orderTransferDetail);
            }

            /*if(transferCourseId != null){
                if(isAll == true){
                    //把所在班级设置为转出状态
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("order_detail_id",transferCourseId);
                    //studentGradeQueryWrapper.orderByDesc("created_at");
                    StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                    if(studentGrade != null){
                        studentGrade.setReadingStatus(ReadingStatusEnum.TURN);
                        studentGrade.setStatus(2);
                        iStudentGradeService.updateById(studentGrade);
                    }
                }
            }*/
        }
        //****************************************转课end***********************************//


        //****************************************退费信息详情 start***********************************//
        if (orderType == Code.ORDER_TYPE_REFUND) {
            Long refundCourseId = null;
            Boolean isAll = true;//是否全部退出

            List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();
            Iterator<OrderTransferDetail> orderTransferDetailIterator = orderApply.getOrderTransferDetailList().iterator();
            while (orderTransferDetailIterator.hasNext()) {
                OrderTransferDetail orderTransferDetail = orderTransferDetailIterator.next();
                orderTransferDetail.setOrderType(orderApply.getOrderType());
                orderTransferDetail.setOrderId(orderApply.getId());//设置对应的新订单id

                //退费
                OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                yearPart = orderDetail.getYearPart();
                quarterNum = orderDetail.getQuarterNum();
                subjectsId = orderDetail.getSubjectsId();
                if (orderDetail != null) {
                    refundCourseId = orderDetail.getId();

                    OrderDetail newOrderDetail = new OrderDetail();
                    newOrderDetail.setId(orderDetail.getId());
                    Integer outCourseHouse = orderTransferDetail.getOutHouse();
                    Integer courseHouse = orderDetail.getResidueCourseCount() - outCourseHouse;//剩余课时
                    //退费课时不能大于剩余课时
                    if (courseHouse < 0) {
                        throw new CommonException(ResultCode.REFUND_COURSE_BIG);
                    } else if (courseHouse == 0) {
                        try {
                            // 记上课表里使用课时为0，就把排班删除，如果记上课表里使用不为0，如果排班里is_last为1的排班使用课时为0，就删除这条排班，把使用课时大于0的最后一条排班is_last设置为1
                            QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
                            recordCourseQueryWrapper.eq("student_id", orderApply.getStudentId());
                            recordCourseQueryWrapper.eq("year_part", orderDetail.getYearPart());
                            recordCourseQueryWrapper.eq("quarter", orderDetail.getQuarterNum());
                            recordCourseQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
                            recordCourseQueryWrapper.eq("lesson_type", 1);
                            recordCourseQueryWrapper.eq("status", 1);
                            Long recordCourseCount = iRecordCourseService.count(recordCourseQueryWrapper);

                            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                            studentGradeQueryWrapper.eq("student_id", orderApply.getStudentId());
                            studentGradeQueryWrapper.eq("year_part", orderDetail.getYearPart());
                            studentGradeQueryWrapper.eq("quarter_num", orderDetail.getQuarterNum());
                            studentGradeQueryWrapper.eq("lesson_type", 1);
                            studentGradeQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
//                            studentGradeQueryWrapper.eq("status", 1);
//                            studentGradeQueryWrapper.in("reading_status", 0, 1);
                            studentGradeQueryWrapper.eq("deleted", 0);
                            Long studentGradeCount = iStudentGradeService.count(studentGradeQueryWrapper);

                            if (studentGradeCount == 1) {
                                studentGradeQueryWrapper.eq("is_last", 1);
                                StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                                if (studentGrade != null) {
                                    if (recordCourseCount == 0) {
                                        // 删除排班数据
                                        iStudentGradeService.removeById(studentGrade);
                                    }
                                }
                            } else if (studentGradeCount > 1) {
                                List<StudentGrade> studentGrades = iStudentGradeService.list(studentGradeQueryWrapper);
                                for (StudentGrade studentGrade : studentGrades) {
                                    if (studentGrade.getUseCourseCount() == 0) {
                                        iStudentGradeService.removeById(studentGrade);
                                    } else if (studentGrade.getUseCourseCount() > 0) {
                                        //更新为最后一条
                                        QueryWrapper<StudentGrade> studentGradeQueryWrapperNew = new QueryWrapper<>();
                                        studentGradeQueryWrapperNew.eq("year_part", studentGrade.getYearPart());
                                        studentGradeQueryWrapperNew.eq("quarter_num", studentGrade.getQuarterNum());
                                        studentGradeQueryWrapperNew.eq("student_id", studentGrade.getStudentId());
                                        studentGradeQueryWrapperNew.ne("status", 3);
                                        studentGradeQueryWrapperNew.eq("subjects_id", studentGrade.getSubjectsId());
                                        studentGradeQueryWrapperNew.eq("lesson_type", studentGrade.getLessonType());
                                        studentGradeQueryWrapperNew.orderByDesc("id");
                                        List<StudentGrade> studentGradeListNew = iStudentGradeService.list(studentGradeQueryWrapperNew);
                                        Integer i = 0;
                                        for (StudentGrade studentGradeNew : studentGradeListNew) {
                                            if (i == 0) {
                                                studentGradeNew.setIsLast(1);
                                                studentGradeNew.setReadingStatus(ReadingStatusEnum.RETREAT);// 调整为退费
                                            } else {
                                                studentGradeNew.setIsLast(0);
                                            }
                                            iStudentGradeService.updateById(studentGradeNew);
                                            i++;
                                        }
                                        studentGradeQueryWrapperNew.clear();
                                    }
                                }
                            }

                            // 退费删除智能课、刷题班的排班数据
                            QueryWrapper<StudentGrade> studentGradeQueryWrapper2 = new QueryWrapper<>();
                            studentGradeQueryWrapper2.eq("student_id", orderApply.getStudentId());
                            studentGradeQueryWrapper2.eq("year_part", orderDetail.getYearPart());
                            studentGradeQueryWrapper2.eq("quarter_num", orderDetail.getQuarterNum());
                            studentGradeQueryWrapper2.ne("lesson_type", 1);
                            studentGradeQueryWrapper2.eq("subjects_id", orderDetail.getSubjectsId());
                            iStudentGradeService.remove(studentGradeQueryWrapper2);
                        } catch (Exception ex) {
                            System.err.println(ex.getMessage());
                        }

                        //剩余课时为0，表示全部退出
                        newOrderDetail.setReadingStatus(ReadingStatusEnum.RETREAT);

                        StudentGrade studentGrade = iStudentGradeService.getById(orderDetail.getId());
                        if (studentGrade != null) {
                            if (studentGrade.getUseCourseCount() == 0) {
                                iStudentSchoolService.removeById(studentGrade);
                            }
                        }

                        //把所在班级设置为退费状态
                        UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                        //studentGradeUpdateWrapper.set("status",2);
                        //studentGradeUpdateWrapper.set("reading_status", ReadingStatusEnum.FINISH.getKey());
                        //studentGradeUpdateWrapper.eq("order_detail_id", orderDetail.getId());

                        studentGradeUpdateWrapper.eq("school_id", orderDetail.getSchoolId());
                        studentGradeUpdateWrapper.eq("year_part", orderDetail.getYearPart());
                        studentGradeUpdateWrapper.eq("quarter_num", orderDetail.getQuarterNum());
                        studentGradeUpdateWrapper.eq("subjects_id", orderDetail.getSubjectsId());
                        studentGradeUpdateWrapper.eq("student_id", orderDetail.getStudentId());
                        studentGradeUpdateWrapper.in("reading_status", 1, 4, 5);
                        studentGradeUpdateWrapper.set("reading_status", ReadingStatusEnum.RETREAT.getKey());
                        iStudentGradeService.update(null, studentGradeUpdateWrapper);

                        /**
                         * 缴费信息
                         */
                        QueryWrapper<RatePay> ratePayQueryWrapper = new QueryWrapper<>();
                        ratePayQueryWrapper.eq("order_id", orderTransferDetail.getOldOrderId());
                        iRatePayService.remove(ratePayQueryWrapper);

                        QueryWrapper<LackCourseLog> lackCourseLogQueryWrapper = new QueryWrapper<>();
                        lackCourseLogQueryWrapper.eq("student_id", orderDetail.getStudentId());
                        lackCourseLogQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
                        lackCourseLogQueryWrapper.eq("year_part", orderDetail.getYearPart());
                        lackCourseLogQueryWrapper.eq("lesson_type", orderDetail.getLessonType());
                        lackCourseLogQueryWrapper.eq("quarter_num", orderDetail.getQuarterNum());
                        lackCourseLogQueryWrapper.ne("is_repair", 1);
                        iLackCourseLogService.remove(lackCourseLogQueryWrapper);


                        //修改续班状态为退费
                        //iRenewClassService.update(null,new LambdaUpdateWrapper<RenewClass>().eq(RenewClass::getOrderDetailId,orderDetail.getId()).set(RenewClass::getStatus,3).set(RenewClass::getOrderStatus,3));

                    } else if (courseHouse > 0) {
                        isAll = false;
                    }

                    //剩余课时
                    newOrderDetail.setResidueCourseCount(courseHouse);//剩余课时
                    BigDecimal outPrice = orderDetail.getOutPrice();//退出金额

                    //累计退出金额
                    BigDecimal allOutPrice = outPrice.add(orderTransferDetail.getOutPrice());
                    newOrderDetail.setOutPrice(allOutPrice);
                    newOrderDetail.setOutHouse(orderDetail.getOutHouse() + orderTransferDetail.getOutHouse());//累计退出课时
                    //设置剩余金额
                    BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                    residuePrice = residuePrice.subtract(orderTransferDetail.getOutPrice());
                    newOrderDetail.setResiduePrice(residuePrice);
                    orderDetailMapper.updateById(newOrderDetail);

                    //招生数据设置为退费,未上满两次课的，设置为退费
                    Integer recordCount = iRecordCourseService.getRecordCountArrive(orderDetail.getYearPart(), orderDetail.getQuarterNum(), orderDetail.getStudentId(), orderDetail.getSubjectsId());
                    if (recordCount < 2) {
                        Long orderId = orderDetail.getOrderId();
                        UpdateWrapper<EnrollInfo> enrollInfoUpdateWrapper = new UpdateWrapper<>();
                        enrollInfoUpdateWrapper.eq("order_id", orderId);
                        enrollInfoUpdateWrapper.set("is_return", 1);
                        enrollInfoMapper.update(null, enrollInfoUpdateWrapper);
                    }
                    Course course = iCourseService.getById(orderDetail.getCourseId());
                    yearClassId = course.getYearClassId().getKey();
                    subjectsIdSet.add(course.getSubjectsId().toString());
                } else {
                    throw new CommonException(ResultCode.REFUND_COURSE_NOT);
                }
                iOrderTransferDetailService.save(orderTransferDetail);
                //orderTransferDetailList.add(orderTransferDetail);
            }

            try {
                // 获取最后一次上课记录的老师
                RecordCourse recordCourse = iRecordCourseService.getRecordCourseByLastThreeQuarter(yearPart, quarterNum, 1, orderApply.getStudentId(), String.valueOf(subjectsId));
                if (recordCourse != null) {
                    // 保存上课老师到表中
                    OrderReturnTeacher orderReturnTeacher = new OrderReturnTeacher();
                    orderReturnTeacher.setOrderId(orderApply.getId());
                    orderReturnTeacher.setTeacherId(recordCourse.getOldTeacherId());
                    iOrderReturnTeacherService.save(orderReturnTeacher);
                }

                // 添加到退费原因表中
                OrderReturnCause iOrderReturnCause = iOrderReturnCauseService.getOne(new QueryWrapper<OrderReturnCause>()
                        .eq("order_id", orderApply.getId())
                        .last(" limit 1"));

                CommonCause commonCause = iCommonCauseService.getById(orderApply.getCauseId());

                if (iOrderReturnCause == null) {
                    iOrderReturnCause = new OrderReturnCause();
                    iOrderReturnCause.setOrderId(orderApply.getId());
                }

                iOrderReturnCause.setCauseId(orderApply.getCauseId());
                iOrderReturnCause.setCauseContent(commonCause.getContent());
                iOrderReturnCauseService.saveOrUpdate(iOrderReturnCause);

            } catch (Exception ex) {
                System.err.println(ex.getMessage());
            }

            if (isAll == true) {
                //由于有的订单没有分班所以要做如下状态改变
                Long outCourseId = orderApply.getOrderTransfer().getOutGradeId();//转出课程id
                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                studentGradeQueryWrapper.eq("school_id", orderApply.getSchoolId());
                studentGradeQueryWrapper.eq("student_id", orderApply.getStudentId());
                studentGradeQueryWrapper.eq("course_id", outCourseId);
                studentGradeQueryWrapper.eq("status", 1);
                studentGradeQueryWrapper.eq("reading_status", 1);

                List<StudentGrade> studentGradeListUp = iStudentGradeService.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade : studentGradeListUp) {
                    if (studentGrade.getUseCourseCount() == 0) {
                        iStudentSchoolService.removeById(studentGrade);
                    } else {
                        studentGrade.setReadingStatus(ReadingStatusEnum.RETREAT);
                        iStudentGradeService.updateById(studentGrade);
                    }
                }
            }



            /*if(refundCourseId != null){
                if(isAll == true){
                    //把所在班级设置为退费状态
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("course_id",refundCourseId);
                    studentGradeQueryWrapper.orderByDesc("created_at");
                    StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                    if(studentGrade != null){
                        studentGrade.setReadingStatus(ReadingStatusEnum.RETREAT);
                        studentGrade.setStatus(2);
                        iStudentGradeService.updateById(studentGrade);
                    }
                }
            }*/
        }
        //****************************************补费，转课，退费信息详情 end***********************************//


        //*************************************续班率start**************************************************//
        if (renewClassesList.size() > 0) {
            iRenewClassService.saveBatch(renewClassesList, renewClassesList.size());
        }
        //*************************************续班率end**************************************************//
        orderApply.setYearPart(yearPart);
        orderApply.setQuarterNum(quarterNum);
        orderApply.setTradeContent(tradeContent);
        orderApply.setYearClassId(yearClassId);
        if (subjectsIdSet.size() > 0) {
            //String subjectsIds = String.join(",", subjectsIdSet.stream().map(String::valueOf).toList());
            String subjectsIds = String.join(",", subjectsIdSet);
            orderApply.setSubjectsIdStr(subjectsIds);
        }


        //this.save(orderApply);
        orderApplyMapper.updateById(orderApply);

        //招生信息
        try {
            if (orderType == Code.ORDER_TYPE_SiGN) {
                if (student.getStuType().equals(2)) {
                    student.setStuType(1);
                    iStudentService.updateById(student);
                }
                if (applyCount.equals(0L)) {
                    EnrollSet enrollSet = iEnrollSetService.findEnrollSetForDate(orderApply.getSchoolId());
                    LocalDate localDate = LocalDate.now();
                    BigDecimal inviteMoney = enrollSet.getPushMoney1();
                    BigDecimal auditionMoney = enrollSet.getPushMoney2();
                    BigDecimal bargainMoney = enrollSet.getPushMoney3();
                    //邀约:1
                    if (orderApply.getInviteList() != null) {
                        Integer inviteCount = orderApply.getInviteList().size();
                        if (inviteCount > 0) {
                            Double dealNum = 1.0 / inviteCount;
                            for (Long id : orderApply.getInviteList()) {
                                Long teamId = iEnrollTeamMemberService.getTeamIdForteacherId(id);
                                EnrollInfo enrollInfo = new EnrollInfo();
                                enrollInfo.setTeacherId(id);
                                enrollInfo.setSubjectsId(subjectsId);
                                enrollInfo.setStudentId(orderApply.getStudentId());
                                enrollInfo.setTeamId(teamId);
                                enrollInfo.setOrderId(orderApply.getId());
                                enrollInfo.setSchoolId(orderApply.getSchoolId());
                                enrollInfo.setDealNum(dealNum);
                                enrollInfo.setPushMoney(inviteMoney.divide(new BigDecimal(inviteCount), 2, BigDecimal.ROUND_HALF_UP));
                                enrollInfo.setAddDate(localDate);
                                enrollInfo.setType(1);
                                enrollInfoMapper.insert(enrollInfo);
                            }
                        }
                    }

                    if (orderApply.getAuditionList() != null) {
                        //试听:2
                        Integer auditionCount = orderApply.getAuditionList().size();
                        if (auditionCount > 0) {
                            Double dealNum = 1.0 / auditionCount;
                            for (Long id : orderApply.getAuditionList()) {
                                Long teamId = iEnrollTeamMemberService.getTeamIdForteacherId(id);
                                EnrollInfo enrollInfo = new EnrollInfo();
                                enrollInfo.setTeacherId(id);
                                enrollInfo.setSubjectsId(subjectsId);
                                enrollInfo.setStudentId(orderApply.getStudentId());
                                enrollInfo.setTeamId(teamId);
                                enrollInfo.setOrderId(orderApply.getId());
                                enrollInfo.setSchoolId(orderApply.getSchoolId());
                                enrollInfo.setDealNum(dealNum);
                                enrollInfo.setPushMoney(auditionMoney.divide(new BigDecimal(auditionCount), 2, BigDecimal.ROUND_HALF_UP));
                                enrollInfo.setAddDate(localDate);
                                enrollInfo.setType(2);
                                enrollInfoMapper.insert(enrollInfo);
                            }
                        }
                    }

                    if (orderApply.getBargainList() != null) {
                        //成交:3
                        Integer bargainCount = orderApply.getBargainList().size();
                        if (bargainCount > 0) {
                            Double dealNum = 1.0 / bargainCount;
                            for (Long id : orderApply.getBargainList()) {
                                Long teamId = iEnrollTeamMemberService.getTeamIdForteacherId(id);
                                EnrollInfo enrollInfo = new EnrollInfo();
                                enrollInfo.setTeacherId(id);
                                enrollInfo.setSubjectsId(subjectsId);
                                enrollInfo.setStudentId(orderApply.getStudentId());
                                enrollInfo.setTeamId(teamId);
                                enrollInfo.setOrderId(orderApply.getId());
                                enrollInfo.setSchoolId(orderApply.getSchoolId());
                                enrollInfo.setDealNum(dealNum);
                                enrollInfo.setPushMoney(bargainMoney.divide(new BigDecimal(bargainCount), 2, BigDecimal.ROUND_HALF_UP));
                                enrollInfo.setAddDate(localDate);
                                enrollInfo.setType(3);
                                enrollInfoMapper.insert(enrollInfo);
                            }
                        }
                    }
                    if (enrollSet.getPushMoney4() != null && enrollSet.getPushMoney4().compareTo(BigDecimal.ZERO) > 0) {
                        //添加号码人信息
                        EnrollCustomer enrollCustomer = iEnrollSetService.getPhoneCustomer(student.getId());
                        if (enrollCustomer != null) {
                            Long teamId = iEnrollTeamMemberService.getTeamIdForteacherId(enrollCustomer.getTeacherId());
                            EnrollInfo enrollInfo = new EnrollInfo();
                            enrollInfo.setTeacherId(enrollCustomer.getTeacherId());
                            enrollInfo.setSubjectsId(subjectsId);
                            enrollInfo.setStudentId(orderApply.getStudentId());
                            enrollInfo.setTeamId(teamId);
                            enrollInfo.setOrderId(orderApply.getId());
                            enrollInfo.setSchoolId(orderApply.getSchoolId());
                            enrollInfo.setDealNum(new Double(1));
                            enrollInfo.setPushMoney(enrollSet.getPushMoney4());
                            enrollInfo.setAddDate(localDate);
                            enrollInfo.setType(4);//拿号码
                            enrollInfoMapper.insert(enrollInfo);
                        } else {
                            if (orderApply.getInviteList() != null) {
                                Integer inviteCount = orderApply.getInviteList().size();
                                if (inviteCount > 0) {
                                    Double dealNum = 1.0 / inviteCount;
                                    for (Long id : orderApply.getInviteList()) {
                                        Long teamId = iEnrollTeamMemberService.getTeamIdForteacherId(id);
                                        EnrollInfo enrollInfo = new EnrollInfo();
                                        enrollInfo.setTeacherId(id);
                                        enrollInfo.setSubjectsId(subjectsId);
                                        enrollInfo.setStudentId(orderApply.getStudentId());
                                        enrollInfo.setTeamId(teamId);
                                        enrollInfo.setOrderId(orderApply.getId());
                                        enrollInfo.setSchoolId(orderApply.getSchoolId());
                                        enrollInfo.setDealNum(dealNum);
                                        enrollInfo.setPushMoney(enrollSet.getPushMoney4().divide(new BigDecimal(inviteCount), 2, BigDecimal.ROUND_HALF_UP));
                                        enrollInfo.setAddDate(localDate);
                                        enrollInfo.setType(4);//拿号码
                                        enrollInfoMapper.insert(enrollInfo);
                                    }
                                }
                            }
                        }

                        // 新生添加到student_news表
                        if (orderApply.getIsAddLack() != null) {
                            if (subjectsIdSet.size() > 0) {
                                String subjectsIds = String.join(",", subjectsIdSet);
                                // 逗号拆分科目
                                String[] subjectsIdArr = subjectsIds.split(",");
                                for (String subjectIdArr : subjectsIdArr) {
                                    StudentNews studentNews = new StudentNews();
                                    studentNews.setStudentId(orderApply.getStudentId());
                                    studentNews.setOrderId(orderApply.getId());
                                    studentNews.setYearPart(orderApply.getYearPart());
                                    studentNews.setQuarterNum(orderApply.getQuarterNum());
                                    studentNews.setSubjectsId(Long.valueOf(subjectIdArr));
                                    studentNews.setIsAddLack(orderApply.getIsAddLack());
                                    iStudentNewsService.addStudentNews(studentNews);
                                }
                            }
                        }

                    }

                    EnrollInfoGrantSchool enrollInfoGrantSchool = new EnrollInfoGrantSchool();
                    enrollInfoGrantSchool.setGrantNum(new BigDecimal(1));
                    enrollInfoGrantSchool.setOrderId(orderApply.getId());
                    enrollInfoGrantSchool.setSchoolId(orderApply.getSchoolId());
                    enrollInfoGrantSchool.setStudentId(orderApply.getStudentId());
                    enrollInfoGrantSchool.setSubjectsId(subjectsId);
                    iEnrollInfoGrantSchoolService.save(enrollInfoGrantSchool);

                }
            }


        } catch (Exception e) {
        }
        return true;
    }

    @Override
    public boolean saveToMore(OrderApplyMoreRs orderApplyMoreRs) throws ParseException {
        for (OrderApply orderApply : orderApplyMoreRs.getOrderApplyList()) {
            this.saveTo(orderApply);
        }
        return true;
    }


    /**
     * updateDate
     *
     * @param orderApply
     * @return
     */
    public boolean updateDate(OrderApply orderApply) {
        OrderApply orderApplyCount = orderApplyMapper.selectById(orderApply.getId());
        if (orderApplyCount == null) {
            throw new CommonException(ResultCode.ORDERDETAIL_NOT);
        }

        UpdateWrapper<OrderApply> orderApplyUpdateWrapper = new UpdateWrapper<>();
        orderApplyUpdateWrapper.eq("id", orderApply.getId());
        orderApplyUpdateWrapper.set("handle_date", orderApply.getHandleDate());
        orderApplyMapper.update(null, orderApplyUpdateWrapper);

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("order_id", orderApply.getId());

        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);
        QueryWrapper<RenewData> renewDataQueryWrapper = new QueryWrapper<>();
        for (OrderDetail orderDetail : orderDetailList) {

            renewDataQueryWrapper.eq("student_id", orderDetail.getStudentId());
            renewDataQueryWrapper.eq("school_id", orderDetail.getSchoolId());
            renewDataQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
            renewDataQueryWrapper.eq("year_part_renew", orderDetail.getYearPart());
            renewDataQueryWrapper.eq("quarter_num_renew", orderDetail.getQuarterNum());

            List<RenewData> renewDataList = iRenewDataService.list(renewDataQueryWrapper);
            for (RenewData renewData : renewDataList) {
                if (renewData.getRenewDate() != null && renewData.getRenewDate().equals(orderDetail.getHandleDate())) {
                    renewData.setRenewDate(orderApply.getHandleDate());
                    iRenewDataService.updateById(renewData);
                }
            }
            orderDetail.setHandleDate(orderApply.getHandleDate());
            iOrderDetailService.updateById(orderDetail);
        }

        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        enrollInfoQueryWrapper.eq("order_id", orderApply.getId());
        List<EnrollInfo> enrollInfoList = enrollInfoMapper.selectList(enrollInfoQueryWrapper);
        for (EnrollInfo enrollInfo : enrollInfoList) {
            enrollInfo.setAddDate(orderApply.getHandleDate());
            enrollInfoMapper.updateById(enrollInfo);
        }

        UpdateWrapper<RatePay> ratePayUpdateWrapper = new UpdateWrapper<>();
        ratePayUpdateWrapper.set("add_date", orderApply.getHandleDate());
        ratePayUpdateWrapper.eq("order_id", orderApply.getId());
        iRatePayService.update(null, ratePayUpdateWrapper);

        //修改优惠日期
        UpdateWrapper<OrderDisPrice> orderDisPriceUpdateWrapper = new UpdateWrapper<>();
        orderDisPriceUpdateWrapper.eq("dis_order_id", orderApply.getId());
        orderDisPriceUpdateWrapper.set("add_date", orderApply.getHandleDate());
        iOrderDisPriceService.update(orderDisPriceUpdateWrapper);

        // 修改是否为新生
        Quarter quarter = iQuarterService.getNowQuarter();
        Integer yearPart = quarter.getYearPart();
        Integer quarterNum = quarter.getNum();
        Integer gradeSection = CommonUtil.getGradeSection(orderApplyCount.getYearClassId());

        Integer num = 0;
        if (quarter.getType() == 1) {
            num = 7;
        } else if (quarter.getType() == 2) {
            num = 3;
        }

        LocalDate date = LocalDate.now();
        LocalDate endDate = iCourseSchedulingAlwaysService.getEndDate(yearPart, quarterNum, gradeSection, num);
        try {
            if (endDate != null && date.isAfter(endDate)) {
                List<RadeExcludeStudent> radeExcludeStudents = radeExcludeStudentMapper.getRadeExcludeStudentList(orderApplyCount.getSubjectsIdStr(), orderApplyCount.getYearPart(), orderApplyCount.getQuarterNum(), orderApplyCount.getStudentId());

                if (radeExcludeStudents != null && !radeExcludeStudents.isEmpty()) {
                    for (RadeExcludeStudent radeExcludeStudent : radeExcludeStudents) {
                        String subjectsIds = radeExcludeStudent.getSubjectsIds();
                        String schoolIds = radeExcludeStudent.getSchoolIds();
                        String subjectToRemove = orderApplyCount.getSubjectsIdStr();
                        String schoolIdToRemove = String.valueOf(orderApplyCount.getSchoolId());
                        if (subjectsIds == null || subjectsIds.isEmpty()) {
                            continue;

                        }// 移除对应的科目
                        List<String> subjectList = Arrays.asList(subjectsIds.split(","));
                        List<String> updatedSubjectList = subjectList.stream()
                                .filter(subject -> !subject.equals(subjectToRemove))
                                .collect(Collectors.toList());

                        // 移除对应的校区
                        List<String> schoolList = Arrays.asList(schoolIds.split(","));
                        List<String> updatedSchoolList = schoolList.stream()
                                .filter(subject -> !subject.equals(schoolIdToRemove))
                                .collect(Collectors.toList());

                        if (updatedSubjectList.isEmpty()) {
                            // 如果没有剩余科目，即删除记录
                            radeExcludeStudent.setDeleted(1);
                            radeExcludeStudentMapper.updateById(radeExcludeStudent);
                        } else {
                            // 更新剩余的科目和校区
                            String updatedSubjectsIds = String.join(",", updatedSubjectList);
                            String updatedSchoolIds = String.join(",", updatedSchoolList);
                            radeExcludeStudent.setSubjectsIds(updatedSubjectsIds);
                            radeExcludeStudent.setSchoolIds(updatedSchoolIds);
                            radeExcludeStudentMapper.updateById(radeExcludeStudent);
                        }
                        iMqPushService.listRadeExcludeStudent(radeExcludeStudent);
                    }
                }
            }
        } catch (Exception E) {
        }


        return true;
    }

    /**
     * 转校
     *
     * @param orderApply
     * @return
     * @throws ParseException
     */
    @Transactional
    public boolean transferSchoolSave(OrderApply orderApply) throws ParseException {

        Long orderNo = idWorker.nextId();

        OrderApply inOrderApply = (OrderApply) orderApply.clone();//转校用的
        OrderApply returnOrderApply = (OrderApply) orderApply.clone();//转校用的

        inOrderApply.setOrderNo(orderNo.toString());
        returnOrderApply.setOrderNo(orderNo.toString());


        inOrderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);//退费和转校两个都设置为一样的状态
        returnOrderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);//退费和转校两个都设置为一样的状态

        Integer orderType = returnOrderApply.getOrderType().getKey();
        String tradeContent = "";//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元
        OrderTransfer orderTransfer = returnOrderApply.getOrderTransfer();

        if (orderTransfer.getOutSchoolId().equals(orderTransfer.getInSchoolId())) {
            throw new CommonException(ResultCode.SCHOOL_NOT_EQUAL);
        } else {
            //System.out.print(orderTransfer.getOutSchoolId()+"==="+orderTransfer.getInSchoolId());
        }
        Integer outYearPart = 0;
        Integer outQuarterNum = 0;
        Long outCourseId = 0L;//转出课程


        Long outSchoolId = 0L;
        Long outSubjectsId = 0L;
        Long outStudentId = 0L;
        Long inSchoolId = 0L;

        //****************************************退费信息详情 start***********************************//
        Long subjectId = 0L;
        Integer yearClassId = null;
        Iterator<OrderDetail> orderDetailIteratorTurn = inOrderApply.getOrderDetailList().iterator();
        while (orderDetailIteratorTurn.hasNext()) {
            OrderDetail orderDetail = orderDetailIteratorTurn.next();
            Course course = iCourseService.getById(orderDetail.getCourseId());
            subjectId = course.getSubjectsId();
            yearClassId = course.getYearClassId().getKey();
        }

        if (orderType == Code.ORDER_TYPE_TRANSFERSCHOOL) {
            returnOrderApply.setCostType(2);//1收入，2支出
            returnOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
            returnOrderApply.setSchoolId(orderTransfer.getOutSchoolId());//所属校区
            returnOrderApply.setHandleSchoolId(orderTransfer.getOutSchoolId());
            returnOrderApply.setPrice(orderTransfer.getOutPrice());//设置退费金额
            returnOrderApply.setSolidPrice(orderTransfer.getOutPrice());//实收金额
            returnOrderApply.setSubjectsIdStr(subjectId.toString());
            returnOrderApply.setYearClassId(yearClassId);
            orderApplyMapper.insert(returnOrderApply);

            Long refundCourseId = null;
            //Boolean isAll = true;//是否全部退出

            StringBuilder outCourseNames = new StringBuilder();

            List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();
            Iterator<OrderTransferDetail> orderTransferDetailIterator = returnOrderApply.getOrderTransferDetailList().iterator();
            while (orderTransferDetailIterator.hasNext()) {
                OrderTransferDetail orderTransferDetail = orderTransferDetailIterator.next();
                orderTransferDetail.setOrderType(returnOrderApply.getOrderType());
                orderTransferDetail.setOrderId(returnOrderApply.getId());//设置对应的新订单id

                if (!orderTransferDetail.getOutHouse().equals(0)) {
                    //退费
                    OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());

                    Course outCourse = iCourseService.getById(orderDetail.getCourseId());
                    //System.out.println("outCourse");
                    //System.out.println(outCourse);
                    if (outCourse != null) {
                        outCourseId = outCourse.getId();
                        outSubjectsId = outCourse.getSubjectsId();
                        outCourseNames.append(outCourse.getName()).append(",");
                        outQuarterNum = outCourse.getQuarterNum();
                    }

                    outYearPart = orderDetail.getYearPart();
                    //System.out.print("orderDetail===");
                    //System.out.print(orderDetail);

                    if (orderDetail != null) {
                        refundCourseId = orderDetail.getId();

                        OrderDetail newOrderDetail = new OrderDetail();
                        newOrderDetail.setId(orderDetail.getId());

                        Integer outCourseHouse = orderTransferDetail.getOutHouse();
                        Integer courseHouse = orderDetail.getResidueCourseCount() - outCourseHouse;//剩余课时
                        //退费课时不能大于剩余课时
                        if (courseHouse < 0) {
                            throw new CommonException(ResultCode.REFUND_COURSE_BIG);
                        } else if (courseHouse == 0) {

                            try {
                                // 记上课表里使用课时为0，就把排班删除，如果记上课表里使用不为0，如果排班里is_last为1的排班使用课时为0，就删除这条排班，把使用课时大于0的最后一条排班is_last设置为1
                                QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
                                recordCourseQueryWrapper.eq("student_id", orderApply.getStudentId());
                                recordCourseQueryWrapper.eq("year_part", outYearPart);
                                recordCourseQueryWrapper.eq("quarter", outQuarterNum);
                                recordCourseQueryWrapper.eq("subjects_id", returnOrderApply.getSubjectsIdStr());
                                recordCourseQueryWrapper.eq("lesson_type", 1);
                                recordCourseQueryWrapper.eq("status", 1);
                                Long recordCourseCount = iRecordCourseService.count(recordCourseQueryWrapper);

                                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                                studentGradeQueryWrapper.eq("student_id", orderApply.getStudentId());
                                studentGradeQueryWrapper.eq("year_part", outYearPart);
                                studentGradeQueryWrapper.eq("quarter_num", outQuarterNum);
                                studentGradeQueryWrapper.eq("lesson_type", 1);
                                studentGradeQueryWrapper.eq("subjects_id", returnOrderApply.getSubjectsIdStr());
//                            studentGradeQueryWrapper.eq("status", 1);
//                            studentGradeQueryWrapper.in("reading_status", 0, 1);
                                studentGradeQueryWrapper.eq("deleted", 0);
                                Long studentGradeCount = iStudentGradeService.count(studentGradeQueryWrapper);

                                if (studentGradeCount == 1) {
                                    studentGradeQueryWrapper.eq("is_last", 1);
                                    StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                                    if (studentGrade != null) {
                                        if (recordCourseCount == 0) {
                                            // 删除排班数据
                                            iStudentGradeService.removeById(studentGrade);
                                        } else {
                                            //把所在班级设置为转校退费状态
                                            studentGrade.setReadingStatus(ReadingStatusEnum.RETREAT);
                                            studentGrade.setStatus(StatusStudentGradeEnum.TURN);
                                            iStudentGradeService.updateById(studentGrade);
                                        }
                                    }
                                } else if (studentGradeCount > 1) {
                                    List<StudentGrade> studentGrades = iStudentGradeService.list(studentGradeQueryWrapper);
                                    for (StudentGrade studentGrade : studentGrades) {
                                        if (studentGrade.getUseCourseCount() == 0) {
                                            iStudentGradeService.removeById(studentGrade);
                                        } else if (studentGrade.getUseCourseCount() > 0) {
                                            //更新为最后一条
                                            QueryWrapper<StudentGrade> studentGradeQueryWrapperNew = new QueryWrapper<>();
                                            studentGradeQueryWrapperNew.eq("year_part", studentGrade.getYearPart());
                                            studentGradeQueryWrapperNew.eq("quarter_num", studentGrade.getQuarterNum());
                                            studentGradeQueryWrapperNew.eq("student_id", studentGrade.getStudentId());
                                            studentGradeQueryWrapperNew.ne("status", 3);
                                            studentGradeQueryWrapperNew.eq("subjects_id", studentGrade.getSubjectsId());
                                            studentGradeQueryWrapperNew.eq("lesson_type", studentGrade.getLessonType());
                                            studentGradeQueryWrapperNew.orderByDesc("id");
                                            List<StudentGrade> studentGradeListNew = iStudentGradeService.list(studentGradeQueryWrapperNew);
                                            Integer i = 0;
                                            for (StudentGrade studentGradeNew : studentGradeListNew) {
                                                if (i == 0) {
                                                    studentGradeNew.setIsLast(1);
                                                    studentGradeNew.setReadingStatus(ReadingStatusEnum.RETREAT);// 调整为退费
                                                    studentGradeNew.setStatus(StatusStudentGradeEnum.TURN);// 从调班转出调整为转校
                                                } else {
                                                    studentGradeNew.setIsLast(0);
                                                }
                                                iStudentGradeService.updateById(studentGradeNew);
                                                i++;
                                            }
                                            studentGradeQueryWrapperNew.clear();
                                        }
                                    }
                                }

                                // 退费删除智能课、刷题班的排班数据
                                QueryWrapper<StudentGrade> studentGradeQueryWrapper2 = new QueryWrapper<>();
                                studentGradeQueryWrapper2.eq("student_id", orderApply.getStudentId());
                                studentGradeQueryWrapper2.eq("year_part", outYearPart);
                                studentGradeQueryWrapper2.eq("quarter_num", outQuarterNum);
                                studentGradeQueryWrapper2.ne("lesson_type", 1);
                                studentGradeQueryWrapper2.eq("subjects_id", returnOrderApply.getSubjectsIdStr());
                                iStudentGradeService.remove(studentGradeQueryWrapper2);
                            } catch (Exception ex) {
                                System.err.println(ex.getMessage());
                            }

                            //剩余课时为0，表示全部退出
                            newOrderDetail.setReadingStatus(ReadingStatusEnum.RETREAT);

                            //把所在班级设置为转校退费状态
//                            UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
//                            //studentGradeUpdateWrapper.set("status",2);
//                            studentGradeUpdateWrapper.set("reading_status", ReadingStatusEnum.RETREAT.getKey());//设置为退费
//                            studentGradeUpdateWrapper.set("status", 4);//1正常,2（转课）调班转出，3订单作废，4（转校）转出
//                            studentGradeUpdateWrapper.eq("order_detail_id", orderDetail.getId());
//                            studentGradeUpdateWrapper.eq("student_id", orderDetail.getStudentId());
//                            studentGradeUpdateWrapper.eq("school_id", orderDetail.getSchoolId());
//                            studentGradeUpdateWrapper.eq("subjects_id", orderDetail.getSubjectsId());
//                            studentGradeUpdateWrapper.eq("year_part", orderDetail.getYearPart());
//                            studentGradeUpdateWrapper.eq("quarter_num", orderDetail.getQuarterNum());
//                            iStudentGradeService.update(null, studentGradeUpdateWrapper);

                            //修改续班状态为退费
                            //iRenewClassService.update(null,new LambdaUpdateWrapper<RenewClass>().eq(RenewClass::getOrderDetailId,orderDetail.getId()).set(RenewClass::getStatus,3).set(RenewClass::getOrderStatus,3));

                        } else if (courseHouse > 0) {
                            //isAll = false;
                        }

                        //System.out.print("courseHouse:"+courseHouse);
                        //剩余课时
                        newOrderDetail.setResidueCourseCount(courseHouse);//剩余课时
                        BigDecimal outPrice = orderDetail.getTurnOutPrice();
                        if (outPrice == null) {
                            outPrice = BigDecimal.ZERO;
                        }
                        //转校累计退出金额
                        BigDecimal allOutPrice = outPrice.add(orderTransferDetail.getOutPrice());
                        newOrderDetail.setTurnOutPrice(allOutPrice);
                        newOrderDetail.setTurnOutHouse(orderDetail.getTurnOutHouse() + orderTransferDetail.getOutHouse());//累计退出课时
                        //设置剩余金额
                        BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                        residuePrice = residuePrice.subtract(orderTransferDetail.getOutPrice());
                        newOrderDetail.setResiduePrice(residuePrice);

                        //转出课时与金额
                        Integer outRollHouse = orderTransferDetail.getOutHouse();
                        BigDecimal outRollPrice = orderTransferDetail.getOutPrice();

                        //orderDetail.setRollOutHouse(outRollHouse+orderDetail.getRollOutHouse());
                        //orderDetail.setRollOutPrice(outRollPrice.add(orderDetail.getRollOutPrice()));

                        orderDetailMapper.updateById(newOrderDetail);
                    } else {
                        throw new CommonException(ResultCode.REFUND_COURSE_NOT);
                    }
                    iOrderTransferDetailService.save(orderTransferDetail);
                }
                //orderTransferDetailList.add(orderTransferDetail);
            }
            if (outCourseNames.length() > 0) {
                outCourseNames.deleteCharAt(outCourseNames.length() - 1);
            }
            //转校
            if ((orderType == Code.ORDER_TYPE_TRANSFERSCHOOL) && orderTransfer != null) {
                orderTransfer.setOrderId(returnOrderApply.getId());
                iOrderTransferService.save(orderTransfer);
                Course outCourse = iCourseService.getById(orderTransfer.getOutGradeId());
                tradeContent += "转校退费：" + outCourseNames.toString() + "退" + orderTransfer.getOutHouse() + "课次，应退学费" + orderTransfer.getOutPrice() + "元";
            }
            returnOrderApply.setYearPart(outYearPart);
            returnOrderApply.setQuarterNum(outQuarterNum);
            returnOrderApply.setTradeContent(tradeContent);
            int[] randMath = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
            Integer randReceiptNo = CommonUtil.getNotSimple(randMath, 7);
            returnOrderApply.setReceiptNo(randReceiptNo.toString());
            orderApplyMapper.updateById(returnOrderApply);

            try {
                // 获取最后一次上课记录的老师
                RecordCourse recordCourse = iRecordCourseService.getRecordCourseByLastThreeQuarter(outYearPart, outQuarterNum, 1, orderApply.getStudentId(), returnOrderApply.getSubjectsIdStr());

                if (recordCourse != null) {
                    // 保存上课老师到表中
                    OrderReturnTeacher orderReturnTeacher = new OrderReturnTeacher();
                    orderReturnTeacher.setOrderId(returnOrderApply.getId());
                    orderReturnTeacher.setTeacherId(recordCourse.getOldTeacherId());
                    iOrderReturnTeacherService.save(orderReturnTeacher);
                }
            } catch (Exception ex) {
                System.err.println(ex.getMessage());
            }

        }

        //*************************************支付信息start**************************************************//
        List<OrderPayAccount> orderPayAccountList = new ArrayList<>();
        Iterator<OrderPayAccount> orderPayAccountIterator = returnOrderApply.getOrderPayAccountList().iterator();
        while (orderPayAccountIterator.hasNext()) {
            OrderPayAccount orderPayAccount = orderPayAccountIterator.next();
            orderPayAccount.setOrderId(returnOrderApply.getId());
            orderPayAccount.setPrice(orderTransfer.getOutPrice());
            orderPayAccountList.add(orderPayAccount);
        }
        if (orderPayAccountList.size() > 0) {
            iOrderPayAccountService.saveBatch(orderPayAccountList, orderPayAccountList.size());
        }
        //*************************************支付信息end**************************************************//


        //****************************************退费信息详情 end***********************************//

        //*************************************订单详情start**************************************************//
        Long inGradeId = null;
        Integer inCourseHosue = 0;

        tradeContent = "";
        Integer yearPart = 0;
        Integer quarterNum = 0;
        Long subjectsId = 0L;
        //Set<String> subjectsIdSet = new HashSet<>();
        if (orderType == Code.ORDER_TYPE_TRANSFERSCHOOL) {
            inOrderApply.setReceiptNo(orderApply.getReceiptNo());
            inOrderApply.setCostType(1);//1收入，2支出
            inOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);
            inOrderApply.setSchoolId(orderTransfer.getInSchoolId());//所属校区

            //System.out.print("inOrderApplyId:"+inOrderApply.getId());

            orderApplyMapper.insert(inOrderApply);

            List<StudentGrade> studentGradeList = new ArrayList<>();

            //支付详情
            List<OrderDetail> orderDetailList = new ArrayList<>();
            Iterator<OrderDetail> orderDetailIterator = inOrderApply.getOrderDetailList().iterator();
            while (orderDetailIterator.hasNext()) {

                if (orderType == Code.ORDER_TYPE_TRANSFERSCHOOL) {
                    if (tradeContent != "") {
                        tradeContent += "</br>";
                    } else {
                        tradeContent += "转校报名：";
                    }
                }

                OrderDetail orderDetail = orderDetailIterator.next();
                inCourseHosue = orderDetail.getAllCourseCount();
                orderDetail.setHandleDate(inOrderApply.getHandleDate());
                orderDetail.setOrderType(inOrderApply.getOrderType());
                orderDetail.setId(idWorker.nextId());
                orderDetail.setStudentId(inOrderApply.getStudentId());
                orderDetail.setUseCourseCount(0);
                orderDetail.setAllCourseCount(orderDetail.getAllCourseCount());//总课时
                orderDetail.setResidueCourseCount(orderDetail.getAllCourseCount());//剩余课时
                orderDetail.setResiduePrice(orderDetail.getSolidPrice());//优惠金额
                //studentGrade.setSchoolId();
                //studentGrade.setEndDate();

                //studentGrade.setAllCourseCount(orderDetail.getAllCourseCount());
                //studentGrade.setUseCourseCount(0);
                //studentGrade.setResidueCourseCount(orderDetail.getAllCourseCount());
                Course course = iCourseService.getById(orderDetail.getCourseId());
                subjectsId = course.getSubjectsId();
                orderDetail.setCourseName(course.getName());
                orderDetail.setSubjectsId(course.getSubjectsId());
                yearClassId = course.getYearClassId().getKey();

                orderDetail.setLessonType(course.getLessonType());//课程类型
                inOrderApply.setLessonType(course.getLessonType());


                //设置报读的季度
                orderDetail.setQuarterNum(course.getQuarterNum());

                tradeContent += course.getName() + ",";

                //续班信息
                /*RenewClass renewClass = iQuarterService.getRenewForPay(inOrderApply.getStudentId(),orderDetail.getSchoolId(),orderDetail.getSubjectsId(),orderDetail.getCourseId(),orderDetail.getAllCourseCount(),orderType);
                renewClass.setOrderType(inOrderApply.getOrderType().getKey());
                if(renewClass.getReSetIsnew() == 1){
                    orderDetail.setIsNewStudent(1);//设置为新生
                }else {
                    orderDetail.setIsNewStudent(0);
                }*/
                //添加当前报读的续班信息
                Integer year_part = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份
                orderDetail.setYearPart(year_part);
                orderDetail.setYearClassId(course.getYearClassId().getKey());

                yearPart = year_part;
                quarterNum = course.getQuarterNum();

                //年份与季度
                orderDetail.setYearAndQuarter(Integer.parseInt(year_part + "" + course.getQuarterNum()));

                Grade grade = null;

                if (orderDetail.getGradeId() != null) {
                    //分班
                    StudentGrade studentGrade = new StudentGrade();
                    studentGrade.setOrderDetailId(orderDetail.getId());
                    studentGrade.setStudentId(inOrderApply.getStudentId());
                    studentGrade.setSubjectsId(course.getSubjectsId());//科目id
                    studentGrade.setGradeId(orderDetail.getGradeId());
                    studentGrade.setCourseId(orderDetail.getCourseId());
                    studentGrade.setYearPart(year_part);///////////////待重新添加
                    studentGrade.setQuarterNum(course.getQuarterNum());

                    //studentGrade.setOrderDetailId(orderDetail.getId());//设置订单id
                    grade = iGradeService.getById(orderDetail.getGradeId());
                    if (grade != null) {
                        inGradeId = grade.getId();
                        orderDetail.setGradeName(grade.getName());
                        orderDetail.setCourseHouse(grade.getStuDeductHour());
                        studentGrade.setSchoolId(grade.getSchoolId());
                        //orderDetail.setSchoolId(grade.getSchoolId());
                        //tradeContent += grade.getName() + ",";

                        //添加到班级
                        iStudentGradeService.addData(orderDetail.getId(), grade.getSchoolId(), orderApply.getStudentId(), grade.getId(), course.getId(), course.getSubjectsId(), year_part, course.getQuarterNum(), orderDetail.getAllCourseCount(), course.getYearClassId().getKey(), grade.getLessonType(), grade.getCourseTypeId(), 1);

                        //设置续班老师
                        /*if(orderType == Code.ORDER_TYPE_SiGN){
                            studentGrade.setRenewTeacherId(grade.getTeacherId());
                        }else {
                            //转课
                            if(orderDetail.getAllCourseCount()>3){
                                studentGrade.setRenewTeacherId(grade.getTeacherId());
                            }
                        }*/

                    }
                    studentGradeList.add(studentGrade);
                }

                tradeContent += orderDetail.getPrice();

                if (orderDetail.getCoursePriceId() != null) {
                    CoursePricing coursePricing = iCoursePricingService.getById(orderDetail.getCoursePriceId());
                    if (coursePricing != null) {
                        tradeContent += "(" + coursePricing.getCountUnit() + ")*" + orderDetail.getCount() + "=" + orderDetail.getPrice() + "元";
                        orderDetail.setCoursePriceName(coursePricing.getCount() + coursePricing.getCountUnit() + "=" + coursePricing.getAllPrice() + "元");

                        //保存到订单支付价格表
                        OrderCoursePricing orderCoursePricing = new OrderCoursePricing();

                        orderCoursePricing.setId(orderDetail.getId());
                        orderCoursePricing.setPrice(coursePricing.getPrice());
                        orderCoursePricing.setCount(coursePricing.getCount());
                        orderCoursePricing.setCountUnit(coursePricing.getCountUnit());
                        orderCoursePricing.setUnitPrice(coursePricing.getUnitPrice());
                        orderCoursePricing.setChargeMode(coursePricing.getChargeMode());
                        orderCoursePricing.setServePrice(coursePricing.getServePrice());
                        orderCoursePricing.setMaterialsPrice(coursePricing.getMaterialsPrice());
                        orderCoursePricing.setAllPrice(coursePricing.getAllPrice());
                        iOrderCoursePricingService.saveOrUpdate(orderCoursePricing);
                    }
                }
                orderDetail.setOrderId(inOrderApply.getId());

                Long studentId = orderApply.getStudentId();

                //System.out.println("studentId:"+studentId+"--schoolId:"+orderDetail.getSchoolId());
                UpdateWrapper<Student> studentUpdateWrapper = new UpdateWrapper<>();
                studentUpdateWrapper.eq("id", studentId).set("school_id", orderDetail.getSchoolId());
                iStudentService.update(null, studentUpdateWrapper);
                iStudentSchoolService.addOrUpdateData(studentId, orderDetail.getSchoolId());

                QueryWrapper<StudentSchool> studentSchoolQueryWrapper = new QueryWrapper<StudentSchool>();
                studentSchoolQueryWrapper.eq("school_id", orderDetail.getSchoolId());
                studentSchoolQueryWrapper.eq("student_id", orderDetail.getStudentId());
                Long studentSchoolCount = iStudentSchoolService.count(studentSchoolQueryWrapper);
                if (studentSchoolCount.equals(0L)) {
                    StudentSchool studentSchool = new StudentSchool();
                    studentSchool.setId(idWorker.nextId());
                    studentSchool.setSchoolId(orderDetail.getSchoolId());
                    studentSchool.setStudentId(orderDetail.getStudentId());
                    iStudentSchoolService.save(studentSchool);
                }


                //renewClass.setOrderDetailId(orderDetail.getId());
                //renewClassesList.add(renewClass);
                //orderDetail.setYearPart(renewClass.getYearPart());
                iOrderDetailService.save(orderDetail);
                //orderDetailList.add(orderDetail);

                //设置为新生或者老生
                //iStudentTypeService.addData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course.getSubjectsId(),orderDetail.getIsNewStudent());

                //更新续班信息是否成功
                //if(orderType == Code.ORDER_TYPE_SiGN){
                //报名
                //    iRenewDataService.updateData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course,grade,orderDetail.getAllCourseCount(),1);
                //}else {
                //转课
                //    iRenewDataService.updateData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course,grade,orderDetail.getAllCourseCount(),2);

                //}
                //添加当前报读的续班信息
                //iRenewDataService.addData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course,grade);
                iRenewDataService.transferSchoolUpdate(orderApply.getStudentId(), orderTransfer.getOutSchoolId(), outYearPart, orderTransfer.getInSchoolId(), outCourseId, orderTransfer.getInGradeId(), inGradeId, inCourseHosue, orderDetail.getId());

                outStudentId = orderApply.getStudentId();
                outSchoolId = orderTransfer.getOutSchoolId();
                inSchoolId = orderTransfer.getOutSchoolId();

                QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
                studentFaceDataQueryWrapper.eq("school_id", inSchoolId);
                studentFaceDataQueryWrapper.eq("student_id", outStudentId);
                Long count = iStudentFaceDataService.count(studentFaceDataQueryWrapper);
                if (count == 0) {
                    studentFaceDataQueryWrapper.clear();
                    studentFaceDataQueryWrapper.eq("school_id", outSchoolId);
                    studentFaceDataQueryWrapper.eq("student_id", outStudentId);
                    List<StudentFaceData> studentFaceDataList = iStudentFaceDataService.list(studentFaceDataQueryWrapper);
                    for (StudentFaceData studentFaceData : studentFaceDataList) {
                        StudentFaceData studentFaceDataNew = new StudentFaceData();
                        BeanUtils.copyProperties(studentFaceData, studentFaceDataNew);
                        studentFaceDataNew.setId(idWorker.nextId());
                        studentFaceDataNew.setSchoolId(inSchoolId);
                        studentFaceDataNew.setEntityId(0L);
                        studentFaceDataNew.setFaceId("");
                        studentFaceDataNew.setUpdateLevel(1);
                        iStudentFaceDataService.save(studentFaceData);
                    }
                }
                //更新预分班，还没有添加订单id的
                iStudentGradeService.updateOrderDetailId(orderDetail.getYearPart(), orderDetail.getQuarterNum(), orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getId());
            }


            if (orderDetailList.size() > 0) {
                //为了添加交易内容，放在上面一条一条加
                //iOrderDetailService.saveBatch(orderDetailList,orderDetailList.size());
            }
            if (studentGradeList.size() > 0) {
                //iStudentGradeService.saveBatch(studentGradeList,studentGradeList.size());
            }
        }

        //*************************************支付信息start**************************************************//
        orderPayAccountList = new ArrayList<>();
        orderPayAccountIterator = inOrderApply.getOrderPayAccountList().iterator();
        while (orderPayAccountIterator.hasNext()) {
            OrderPayAccount orderPayAccount = orderPayAccountIterator.next();
            orderPayAccount.setId(null);
            orderPayAccount.setOrderId(inOrderApply.getId());
            orderPayAccount.setPrice(inOrderApply.getPrice());
            orderPayAccountList.add(orderPayAccount);
        }
        if (orderPayAccountList.size() > 0) {
            iOrderPayAccountService.saveBatch(orderPayAccountList, orderPayAccountList.size());
        }

        inOrderApply.setYearPart(yearPart);
        inOrderApply.setQuarterNum(quarterNum);
        inOrderApply.setTradeContent(tradeContent);
        inOrderApply.setYearClassId(yearClassId);
        if (subjectsId != null) {
            inOrderApply.setSubjectsIdStr(subjectsId.toString());
        }
        orderApplyMapper.updateById(inOrderApply);
        //*************************************支付信息end**************************************************//

        //****************************************报名信息详情 end***********************************//

        //添加智能课或者刷题班
        try {
            Integer lessonType = 1;//精品课
            //转校
            //iOrderDetailService.addOrderApply(outYearPart,quarterNum,orderTransfer.getOutSchoolId(),outSubjectsId,lessonType,orderApply.getStudentId());
            iOrderDetailService.addOrderApply(yearPart, quarterNum, orderTransfer.getInSchoolId(), subjectsId, lessonType, orderApply.getStudentId());

            //人脸数据，使用了多帐号共用，这里不再需要，因为注释掉
            /*QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
            studentFaceDataQueryWrapper.eq("school_id", outSchoolId);
            studentFaceDataQueryWrapper.eq("student_id", orderApply.getStudentId());
            studentFaceDataQueryWrapper.orderByDesc("id");
            studentFaceDataQueryWrapper.last("limit 1");
            StudentFaceData studentFaceData = iStudentFaceDataService.getOne(studentFaceDataQueryWrapper);
            if (studentFaceData != null) {
                if (!studentFaceData.getSchoolId().equals(orderApply.getSchoolId())) {
                    StudentFaceData studentFaceDataNew = new StudentFaceData();
                    BeanUtils.copyProperties(studentFaceData, studentFaceDataNew);

                    studentFaceDataNew.setId(idWorker.nextId());
                    studentFaceDataNew.setSchoolId(inSchoolId);
                    studentFaceDataNew.setUpdateLevel(100);
                    studentFaceDataNew.setCreatedAt(LocalDateTime.now().withNano(0));
                    iStudentFaceDataService.save(studentFaceDataNew);
                    Boolean rs = iStudentFaceDataService.updateStudentFace(studentFaceDataNew,1);
                }else {
                    if (studentFaceData.getUpdateLevel().equals(100)){
                        Boolean rs = iStudentFaceDataService.setData(studentFaceData.getSchoolId(), studentFaceData.getStudentId().toString(), studentFaceData.getOssImage(), studentFaceData,1);
                    }
                }
            }*/
        } catch (Exception e) {
        }

        return true;
    }

    /**
     * 批量转校
     *
     * @param orderApply
     * @return
     * @throws ParseException
     */
    public Result batchTransferSchoolSave(OrderApply orderApply) throws ParseException {
        Long schoolId = orderApply.getSchoolId();
        Quarter quarterNow = iQuarterService.getNowQuarter();
        Integer lessonType = 1;

        /**
         * 还有请假未被的
         */
        List<String> errorList = new ArrayList<>();
        for (Long studentId : orderApply.getStudentList()) {
            Student student = iStudentService.getById(studentId);
            for (Long subjectsId : orderApply.getSubjectsList()) {
                Integer lackCount = iRecordCourseService.getLackCount(quarterNow.getYearPart(), quarterNow.getNum(), orderApply.getOutSchoolId(), studentId, subjectsId, lessonType);
                if (lackCount > 0) {
                    String errorStr = student.getName() + "," + CommonUtil.getSubjectsNameForId(Integer.parseInt(subjectsId.toString())) + "还有请假未补的记上课，请先处理再转课";
                    errorList.add(errorStr);
                }
            }
        }

        if (errorList.size() > 0) {
            return new Result(Code.ERROR, "", "转校失败：" + String.join(",", errorList));
        }

        String studentIds = orderApply.getStudentList().stream().map(Object::toString).collect(Collectors.joining(","));
        String subjectsIds = orderApply.getSubjectsList().stream().map(Object::toString).collect(Collectors.joining(","));

        String names = this.getNotAffirmStudentName(quarterNow.getYearPart(), quarterNow.getNum(), orderApply.getOutSchoolId(), studentIds, subjectsIds);
        if (StringUtils.isNotBlank(names)) {
            return new Result(Code.ERROR, "", "转校失败，还有“" + names + "”报名订单未确认，请先确认再转校");
        }


        Integer i = 0;
        for (Long studentId : orderApply.getStudentList()) {
            for (Long subjectsId : orderApply.getSubjectsList()) {
                QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
                orderDetailQueryWrapper.eq("student_id", studentId);
                orderDetailQueryWrapper.eq("subjects_id", subjectsId);
                orderDetailQueryWrapper.eq("school_id", orderApply.getOutSchoolId());
                orderDetailQueryWrapper.ne("status", 2);
                orderDetailQueryWrapper.gt("residue_course_count", 0);
                orderDetailQueryWrapper.eq("year_part", quarterNow.getYearPart());
                orderDetailQueryWrapper.eq("quarter_num", quarterNow.getNum());
                orderDetailQueryWrapper.eq("lesson_type", lessonType);

                Long count = orderDetailMapper.selectCount(orderDetailQueryWrapper);
                if (count > 0) {
                    //新数据
                    OrderApply orderApplyNew = this.getOutSchoolDetail(orderApply.getOutSchoolId(), orderApply.getSchoolId(), studentId, subjectsId, lessonType);
                    if (orderApplyNew != null) {
                        orderApplyNew.setHandlePersonId(orderApply.getHandlePersonId());
                        orderApplyNew.setHandlePersonName(orderApply.getHandlePersonName());
                        this.transferSchoolSave(orderApplyNew);
                        //添加智能课或者刷题班
                        try {
                            //Integer lessonType = 1;//精品课
                            //转校
                            //iOrderDetailService.addOrderApply(outYearPart,quarterNum,orderTransfer.getOutSchoolId(),outSubjectsId,lessonType,orderApply.getStudentId());
                            //更新转出校区智能课或刷题班数据
                            iOrderDetailService.addOrderApply(quarterNow.getYearPart(), quarterNow.getNum(), orderApplyNew.getOutSchoolId(), subjectsId, lessonType, studentId);
                        } catch (Exception e) {
                        }
                    } else {
                        String subjectsName = CommonUtil.getSubjectsNameForId(Integer.parseInt(subjectsId.toString()));
                        //System.out.println("数据为空,转校失败");
                    }
                }
            }
            i++;
            //System.out.println("count:"+orderApply.getStudentList().size());
            //System.out.println("i:"+i);
        }
        return new Result(Code.OK, "", "");
    }


    /**
     * 转科目（除了科目可以变，其他都不能变）
     *
     * @param orderApply
     * @return
     * @throws ParseException
     */
    @Transactional
    public boolean transferSubjectSave(OrderApply orderApply) throws ParseException {
        Long orderNo = idWorker.nextId();

        OrderApply inOrderApply = (OrderApply) orderApply.clone();//转入（报名）科目用的
        inOrderApply.setOrderNo(orderNo.toString());
        inOrderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SUBJECT);//退费和转科目两个都设置为一样的状态

        OrderApply returnOrderApply = (OrderApply) orderApply.clone();//转出（退费）科目用的
        returnOrderApply.setOrderNo(orderNo.toString());
        returnOrderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SUBJECT);//退费和转科目两个都设置为一样的状态

        Integer orderType = returnOrderApply.getOrderType().getKey();
        StringBuilder tradeContent = new StringBuilder();//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元
        OrderTransfer orderTransfer = returnOrderApply.getOrderTransfer();

        if (!orderTransfer.getOutSchoolId().equals(orderTransfer.getInSchoolId())) {
            // 转科要同校区才可以
            throw new CommonException(ResultCode.SCHOOL_IN_EQUAL);
        }

        Integer outYearPart = 0;
        Integer outQuarterNum = 0;
        Long outCourseId = 0L;//转出课程

        Long outSchoolId = 0L;
        Long outStudentId = 0L;
        Long inSchoolId = 0L;

        //****************************************退费信息详情 start***********************************//
        Integer yearClassId = null;
        Iterator<OrderDetail> orderDetailIteratorTurn = inOrderApply.getOrderDetailList().iterator();
        while (orderDetailIteratorTurn.hasNext()) {
            OrderDetail orderDetail = orderDetailIteratorTurn.next();
            Course course = iCourseService.getById(orderDetail.getCourseId());
            yearClassId = course.getYearClassId().getKey();
        }

        if (orderType == Code.ORDER_TYPE_TRANSFERSUBJECT) {
            returnOrderApply.setCostType(2);//1收入，2支出
            returnOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
            returnOrderApply.setSchoolId(orderTransfer.getOutSchoolId());//所属校区
            returnOrderApply.setHandleSchoolId(orderTransfer.getOutSchoolId());
            returnOrderApply.setPrice(orderTransfer.getOutPrice());//设置退费金额
            returnOrderApply.setSolidPrice(orderTransfer.getOutPrice());//实收金额
            returnOrderApply.setSubjectsIdStr(orderTransfer.getOutSubjectsId());// 设置退费科目
            returnOrderApply.setYearClassId(yearClassId);
            orderApplyMapper.insert(returnOrderApply);

            StringBuilder outCourseNames = new StringBuilder();
            Iterator<OrderTransferDetail> orderTransferDetailIterator = returnOrderApply.getOrderTransferDetailList().iterator();
            while (orderTransferDetailIterator.hasNext()) {
                OrderTransferDetail orderTransferDetail = orderTransferDetailIterator.next();
                orderTransferDetail.setOrderType(returnOrderApply.getOrderType());
                orderTransferDetail.setOrderId(returnOrderApply.getId());//设置对应的新订单id

                if (!orderTransferDetail.getOutHouse().equals(0)) {
                    //退费
                    OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                    Course outCourse = iCourseService.getById(orderDetail.getCourseId());
                    if (outCourse != null) {
                        outCourseId = outCourse.getId();
                        outCourseNames.append(outCourse.getName()).append(",");
                        outQuarterNum = outCourse.getQuarterNum();
                    }

                    outYearPart = orderDetail.getYearPart();

                    if (orderDetail != null) {
                        OrderDetail newOrderDetail = new OrderDetail();
                        newOrderDetail.setId(orderDetail.getId());

                        Integer outCourseHouse = orderTransferDetail.getOutHouse();
                        Integer courseHouse = orderDetail.getResidueCourseCount() - outCourseHouse;//剩余课时
                        //退费课时不能大于剩余课时
                        if (courseHouse < 0) {
                            throw new CommonException(ResultCode.REFUND_COURSE_BIG);
                        } else if (courseHouse == 0) {

                            try {
                                // 记上课表里使用课时为0，就把排班删除，如果记上课表里使用不为0，如果排班里is_last为1的排班使用课时为0，就删除这条排班，把使用课时大于0的最后一条排班is_last设置为1
                                QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
                                recordCourseQueryWrapper.eq("student_id", orderApply.getStudentId());
                                recordCourseQueryWrapper.eq("year_part", outYearPart);
                                recordCourseQueryWrapper.eq("quarter", outQuarterNum);
                                recordCourseQueryWrapper.eq("subjects_id", returnOrderApply.getSubjectsIdStr());
                                recordCourseQueryWrapper.eq("lesson_type", 1);
                                recordCourseQueryWrapper.eq("status", 1);
                                Long recordCourseCount = iRecordCourseService.count(recordCourseQueryWrapper);

                                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                                studentGradeQueryWrapper.eq("student_id", orderApply.getStudentId());
                                studentGradeQueryWrapper.eq("year_part", outYearPart);
                                studentGradeQueryWrapper.eq("quarter_num", outQuarterNum);
                                studentGradeQueryWrapper.eq("lesson_type", 1);
                                studentGradeQueryWrapper.eq("subjects_id", returnOrderApply.getSubjectsIdStr());
//                            studentGradeQueryWrapper.eq("status", 1);
//                            studentGradeQueryWrapper.in("reading_status", 0, 1);
                                studentGradeQueryWrapper.eq("deleted", 0);
                                Long studentGradeCount = iStudentGradeService.count(studentGradeQueryWrapper);

                                if (studentGradeCount == 1) {
                                    studentGradeQueryWrapper.eq("is_last", 1);
                                    StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                                    if (studentGrade != null) {
                                        if (recordCourseCount == 0) {
                                            // 删除排班数据
                                            iStudentGradeService.removeById(studentGrade);
                                        } else {
                                            //把所在班级设置为科目退费状态
                                            studentGrade.setReadingStatus(ReadingStatusEnum.RETREAT);
                                            studentGrade.setStatus(StatusStudentGradeEnum.TURNSUBJECT);
                                            iStudentGradeService.updateById(studentGrade);
                                        }
                                    }
                                } else if (studentGradeCount > 1) {
                                    List<StudentGrade> studentGrades = iStudentGradeService.list(studentGradeQueryWrapper);
                                    for (StudentGrade studentGrade : studentGrades) {
                                        if (studentGrade.getUseCourseCount() == 0) {
                                            iStudentGradeService.removeById(studentGrade);
                                        } else if (studentGrade.getUseCourseCount() > 0) {
                                            //更新为最后一条
                                            QueryWrapper<StudentGrade> studentGradeQueryWrapperNew = new QueryWrapper<>();
                                            studentGradeQueryWrapperNew.eq("year_part", studentGrade.getYearPart());
                                            studentGradeQueryWrapperNew.eq("quarter_num", studentGrade.getQuarterNum());
                                            studentGradeQueryWrapperNew.eq("student_id", studentGrade.getStudentId());
                                            studentGradeQueryWrapperNew.ne("status", 3);
                                            studentGradeQueryWrapperNew.eq("subjects_id", studentGrade.getSubjectsId());
                                            studentGradeQueryWrapperNew.eq("lesson_type", studentGrade.getLessonType());
                                            studentGradeQueryWrapperNew.orderByDesc("id");
                                            List<StudentGrade> studentGradeListNew = iStudentGradeService.list(studentGradeQueryWrapperNew);
                                            Integer i = 0;
                                            for (StudentGrade studentGradeNew : studentGradeListNew) {
                                                if (i == 0) {
                                                    studentGradeNew.setIsLast(1);
                                                    studentGradeNew.setReadingStatus(ReadingStatusEnum.RETREAT);// 调整为退费
                                                    studentGradeNew.setStatus(StatusStudentGradeEnum.TURNSUBJECT);// 从调班转出调整为转科目
                                                } else {
                                                    studentGradeNew.setIsLast(0);
                                                }
                                                iStudentGradeService.updateById(studentGradeNew);
                                                i++;
                                            }
                                            studentGradeQueryWrapperNew.clear();
                                        }
                                    }
                                }

                                // 退费删除智能课、刷题班的排班数据
                                QueryWrapper<StudentGrade> studentGradeQueryWrapper2 = new QueryWrapper<>();
                                studentGradeQueryWrapper2.eq("student_id", orderApply.getStudentId());
                                studentGradeQueryWrapper2.eq("year_part", outYearPart);
                                studentGradeQueryWrapper2.eq("quarter_num", outQuarterNum);
                                studentGradeQueryWrapper2.ne("lesson_type", 1);
                                studentGradeQueryWrapper2.eq("subjects_id", returnOrderApply.getSubjectsIdStr());
                                iStudentGradeService.remove(studentGradeQueryWrapper2);

                                List<Long> ratePayIds = iRatePayService.getIdsByUseCourseCount(orderApply.getStudentId(), Long.parseLong(returnOrderApply.getSubjectsIdStr()), outYearPart, outQuarterNum);
                                for (Long id : ratePayIds) {
                                    iRatePayService.removeById(id);
                                }

                            } catch (Exception ex) {
                                System.err.println(ex.getMessage());
                            }

                            //剩余课时为0，表示全部退出
                            newOrderDetail.setReadingStatus(ReadingStatusEnum.RETREAT);
//                            //把所在班级设置为转校退费状态
//                            UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
//                            studentGradeUpdateWrapper.set("reading_status", ReadingStatusEnum.RETREAT.getKey());//设置为退费
//                            studentGradeUpdateWrapper.set("status", 5);//1正常,2（转课）调班转出，3订单作废，4（转校）转出，5（转科）转出，6（转名额）转出
//                            studentGradeUpdateWrapper.eq("order_detail_id", orderDetail.getId());
//                            studentGradeUpdateWrapper.eq("student_id", orderDetail.getStudentId());
//                            studentGradeUpdateWrapper.eq("school_id", orderDetail.getSchoolId());
//                            studentGradeUpdateWrapper.eq("subjects_id", orderDetail.getSubjectsId());
//                            studentGradeUpdateWrapper.eq("year_part", orderDetail.getYearPart());
//                            studentGradeUpdateWrapper.eq("quarter_num", orderDetail.getQuarterNum());
//                            iStudentGradeService.update(studentGradeUpdateWrapper);
                        }

                        //剩余课时
                        newOrderDetail.setResidueCourseCount(courseHouse);
                        BigDecimal outPrice = orderDetail.getTurnOutPrice();
                        if (outPrice == null) {
                            outPrice = BigDecimal.ZERO;
                        }
                        //转校累计退出金额
                        BigDecimal allOutPrice = outPrice.add(orderTransferDetail.getOutPrice());
                        newOrderDetail.setTurnOutPrice(allOutPrice);
                        newOrderDetail.setTurnOutHouse(orderDetail.getTurnOutHouse() + orderTransferDetail.getOutHouse());//累计退出课时
                        //设置剩余金额
                        BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                        residuePrice = residuePrice.subtract(orderTransferDetail.getOutPrice());
                        newOrderDetail.setResiduePrice(residuePrice);
                        orderDetailMapper.updateById(newOrderDetail);
                    } else {
                        throw new CommonException(ResultCode.REFUND_COURSE_NOT);
                    }
                    iOrderTransferDetailService.save(orderTransferDetail);
                }
            }
            if (outCourseNames.length() > 0) {
                outCourseNames.deleteCharAt(outCourseNames.length() - 1);
            }
            //转科目
            if ((orderType == Code.ORDER_TYPE_TRANSFERSUBJECT) && orderTransfer != null) {
                orderTransfer.setOrderId(returnOrderApply.getId());
                iOrderTransferService.save(orderTransfer);
                tradeContent.append("转科目退费：").append(outCourseNames.toString()).append("退").append(orderTransfer.getOutHouse()).append("课次，应退学费").append(orderTransfer.getOutPrice()).append("元");
            }
            returnOrderApply.setYearPart(outYearPart);
            returnOrderApply.setQuarterNum(outQuarterNum);
            returnOrderApply.setTradeContent(tradeContent.toString());
            int[] randMath = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
            Integer randReceiptNo = CommonUtil.getNotSimple(randMath, 7);
            returnOrderApply.setReceiptNo(randReceiptNo.toString());
            orderApplyMapper.updateById(returnOrderApply);

            try {
                // 获取最后一次上课记录的老师
                RecordCourse recordCourse = iRecordCourseService.getRecordCourseByLastThreeQuarter(outYearPart, outQuarterNum, 1, orderApply.getStudentId(), returnOrderApply.getSubjectsIdStr());

                if (recordCourse != null) {
                    // 保存上课老师到表中
                    OrderReturnTeacher orderReturnTeacher = new OrderReturnTeacher();
                    orderReturnTeacher.setOrderId(returnOrderApply.getId());
                    orderReturnTeacher.setTeacherId(recordCourse.getOldTeacherId());
                    iOrderReturnTeacherService.save(orderReturnTeacher);
                }
            } catch (Exception ex) {
                System.err.println(ex.getMessage());
            }

        }

        //*************************************支付信息start**************************************************//
        List<OrderPayAccount> orderPayAccountList = new ArrayList<>();
        Iterator<OrderPayAccount> orderPayAccountIterator = returnOrderApply.getOrderPayAccountList().iterator();
        while (orderPayAccountIterator.hasNext()) {
            OrderPayAccount orderPayAccount = orderPayAccountIterator.next();
            orderPayAccount.setOrderId(returnOrderApply.getId());
            orderPayAccount.setPrice(orderTransfer.getOutPrice());
            orderPayAccountList.add(orderPayAccount);
        }
        if (orderPayAccountList.size() > 0) {
            iOrderPayAccountService.saveBatch(orderPayAccountList, orderPayAccountList.size());
        }
        //*************************************支付信息end**************************************************//


        //****************************************退费信息详情 end***********************************//

        //*************************************订单详情start**************************************************//
        Long inGradeId = null;
        Integer inCourseHosue = 0;

        tradeContent = new StringBuilder();
        Integer yearPart = 0;
        Integer quarterNum = 0;
        Long subjectsId = 0L;
        if (orderType == Code.ORDER_TYPE_TRANSFERSUBJECT) {
            inOrderApply.setReceiptNo(orderApply.getReceiptNo());
            inOrderApply.setCostType(1);//1收入，2支出
            inOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SUBJECT);
            inOrderApply.setSchoolId(orderTransfer.getInSchoolId());//所属校区
            orderApplyMapper.insert(inOrderApply);

            List<StudentGrade> studentGradeList = new ArrayList<>();

            //支付详情
            Iterator<OrderDetail> orderDetailIterator = inOrderApply.getOrderDetailList().iterator();
            while (orderDetailIterator.hasNext()) {

                if (orderType == Code.ORDER_TYPE_TRANSFERSUBJECT) {
                    if (!tradeContent.toString().equals("")) {
                        tradeContent.append("</br>");
                    } else {
                        tradeContent.append("转科目报名：");
                    }
                }

                OrderDetail orderDetail = orderDetailIterator.next();
                inCourseHosue = orderDetail.getAllCourseCount();
                orderDetail.setHandleDate(inOrderApply.getHandleDate());
                orderDetail.setOrderType(inOrderApply.getOrderType());
                orderDetail.setId(idWorker.nextId());
                orderDetail.setStudentId(inOrderApply.getStudentId());
                orderDetail.setUseCourseCount(0);
                orderDetail.setAllCourseCount(orderDetail.getAllCourseCount());//总课时
                orderDetail.setResidueCourseCount(orderDetail.getAllCourseCount());//剩余课时
                orderDetail.setResiduePrice(orderDetail.getSolidPrice());//优惠金额
                Course course = iCourseService.getById(orderDetail.getCourseId());
                subjectsId = course.getSubjectsId();
                orderDetail.setCourseName(course.getName());
                orderDetail.setSubjectsId(course.getSubjectsId());
                yearClassId = course.getYearClassId().getKey();
                orderDetail.setLessonType(course.getLessonType());//课程类型
                inOrderApply.setLessonType(course.getLessonType());
                //设置报读的季度
                orderDetail.setQuarterNum(course.getQuarterNum());
                tradeContent.append(course.getName()).append(",");
                //添加当前报读的续班信息
                Integer year_part = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份
                orderDetail.setYearPart(year_part);
                orderDetail.setYearClassId(course.getYearClassId().getKey());
                yearPart = year_part;
                quarterNum = course.getQuarterNum();
                //年份与季度
                orderDetail.setYearAndQuarter(Integer.parseInt(year_part + "" + course.getQuarterNum()));
                Grade grade = null;

                if (orderDetail.getGradeId() != null) {
                    //分班
                    StudentGrade studentGrade = new StudentGrade();
                    studentGrade.setOrderDetailId(orderDetail.getId());
                    studentGrade.setStudentId(inOrderApply.getStudentId());
                    studentGrade.setSubjectsId(course.getSubjectsId());//科目id
                    studentGrade.setGradeId(orderDetail.getGradeId());
                    studentGrade.setCourseId(orderDetail.getCourseId());
                    studentGrade.setYearPart(year_part);
                    studentGrade.setQuarterNum(course.getQuarterNum());
                    grade = iGradeService.getById(orderDetail.getGradeId());
                    if (grade != null) {
                        inGradeId = grade.getId();
                        orderDetail.setGradeName(grade.getName());
                        orderDetail.setCourseHouse(grade.getStuDeductHour());
                        studentGrade.setSchoolId(grade.getSchoolId());

                        //添加到班级
                        iStudentGradeService.addData(orderDetail.getId(), grade.getSchoolId(), orderApply.getStudentId(), grade.getId(), course.getId(), course.getSubjectsId(), year_part, course.getQuarterNum(), orderDetail.getAllCourseCount(), course.getYearClassId().getKey(), grade.getLessonType(), grade.getCourseTypeId(), 1);
                    }
                    studentGradeList.add(studentGrade);
                }

                tradeContent.append(orderDetail.getPrice());

                if (orderDetail.getCoursePriceId() != null) {
                    CoursePricing coursePricing = iCoursePricingService.getById(orderDetail.getCoursePriceId());
                    if (coursePricing != null) {
                        tradeContent.append("(").append(coursePricing.getCountUnit()).append(")*").append(orderDetail.getCount()).append("=").append(orderDetail.getPrice()).append("元");
                        orderDetail.setCoursePriceName(coursePricing.getCount() + coursePricing.getCountUnit() + "=" + coursePricing.getAllPrice() + "元");

                        //保存到订单支付价格表
                        OrderCoursePricing orderCoursePricing = new OrderCoursePricing();
                        orderCoursePricing.setId(orderDetail.getId());
                        orderCoursePricing.setPrice(coursePricing.getPrice());
                        orderCoursePricing.setCount(coursePricing.getCount());
                        orderCoursePricing.setCountUnit(coursePricing.getCountUnit());
                        orderCoursePricing.setUnitPrice(coursePricing.getUnitPrice());
                        orderCoursePricing.setChargeMode(coursePricing.getChargeMode());
                        orderCoursePricing.setServePrice(coursePricing.getServePrice());
                        orderCoursePricing.setMaterialsPrice(coursePricing.getMaterialsPrice());
                        orderCoursePricing.setAllPrice(coursePricing.getAllPrice());
                        iOrderCoursePricingService.saveOrUpdate(orderCoursePricing);
                    }
                }
                orderDetail.setOrderId(inOrderApply.getId());

                Long studentId = orderApply.getStudentId();

                UpdateWrapper<Student> studentUpdateWrapper = new UpdateWrapper<>();
                studentUpdateWrapper.eq("id", studentId).set("school_id", orderDetail.getSchoolId());
                iStudentService.update(null, studentUpdateWrapper);
                iStudentSchoolService.addOrUpdateData(studentId, orderDetail.getSchoolId());

                QueryWrapper<StudentSchool> studentSchoolQueryWrapper = new QueryWrapper<StudentSchool>();
                studentSchoolQueryWrapper.eq("school_id", orderDetail.getSchoolId());
                studentSchoolQueryWrapper.eq("student_id", orderDetail.getStudentId());
                Long studentSchoolCount = iStudentSchoolService.count(studentSchoolQueryWrapper);
                if (studentSchoolCount.equals(0L)) {
                    StudentSchool studentSchool = new StudentSchool();
                    studentSchool.setId(idWorker.nextId());
                    studentSchool.setSchoolId(orderDetail.getSchoolId());
                    studentSchool.setStudentId(orderDetail.getStudentId());
                    iStudentSchoolService.save(studentSchool);
                }
                iOrderDetailService.save(orderDetail);

                iRenewDataService.transferSchoolUpdate(orderApply.getStudentId(), orderTransfer.getOutSchoolId(), outYearPart, orderTransfer.getInSchoolId(), outCourseId, orderTransfer.getInGradeId(), inGradeId, inCourseHosue, orderDetail.getId());

                outStudentId = orderApply.getStudentId();
                outSchoolId = orderTransfer.getOutSchoolId();
                inSchoolId = orderTransfer.getOutSchoolId();

                QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
                studentFaceDataQueryWrapper.eq("school_id", inSchoolId);
                studentFaceDataQueryWrapper.eq("student_id", outStudentId);
                Long count = iStudentFaceDataService.count(studentFaceDataQueryWrapper);
                if (count == 0) {
                    studentFaceDataQueryWrapper.clear();
                    studentFaceDataQueryWrapper.eq("school_id", outSchoolId);
                    studentFaceDataQueryWrapper.eq("student_id", outStudentId);
                    List<StudentFaceData> studentFaceDataList = iStudentFaceDataService.list(studentFaceDataQueryWrapper);
                    for (StudentFaceData studentFaceData : studentFaceDataList) {
                        StudentFaceData studentFaceDataNew = new StudentFaceData();
                        BeanUtils.copyProperties(studentFaceData, studentFaceDataNew);
                        studentFaceDataNew.setId(idWorker.nextId());
                        studentFaceDataNew.setSchoolId(inSchoolId);
                        studentFaceDataNew.setEntityId(0L);
                        studentFaceDataNew.setFaceId("");
                        studentFaceDataNew.setUpdateLevel(1);
                        iStudentFaceDataService.save(studentFaceData);
                    }
                }
                //更新预分班，还没有添加订单id的
                iStudentGradeService.updateOrderDetailId(orderDetail.getYearPart(), orderDetail.getQuarterNum(), orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getId());

                try {
                    StudentGrade studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getYearPart(), orderDetail.getQuarterNum(), course.getLessonType());
                    Grade gradeOld = null;
                    if (studentGrade != null) {
                        gradeOld = iGradeService.getById(studentGrade.getGradeId());
                    }
                    if (gradeOld != null) {
                        RatePay ratePay = new RatePay();
                        ratePay.setSchoolId(inSchoolId);
                        ratePay.setTeacherId(gradeOld.getTeacherId());
                        ratePay.setStudentId(orderDetail.getStudentId());
                        ratePay.setSubjectsId(orderDetail.getSubjectsId());
                        ratePay.setGradeId(gradeOld.getId());
                        ratePay.setYearPart(orderDetail.getYearPart());
                        ratePay.setQuarterNum(orderDetail.getQuarterNum());
                        ratePay.setYearClassId(orderDetail.getYearClassId());
                        ratePay.setOrderId(orderDetail.getOrderId());
                        ratePay.setOrderDetailId(orderDetail.getId());
                        ratePay.setId(idWorker.nextId());
                        ratePay.setNum(1);
                        ratePay.setAddDate(LocalDate.now());
                        ratePay.setCreatedAt(LocalDateTime.now().withNano(0));
                        ratePay.setStatus(1);//如果是lkl创建订单，这里先设置为2，支付成功后，再用回调方法调整为1
                        Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getYearAndQuarter(), course.getLessonType());
                        if (residueCourseCount >= 45) {
                            Integer rayNum = residueCourseCount / 45;
                            ratePay.setNum(rayNum);
                            iRatePayService.save(ratePay);
                        }
                    }
                } catch (Exception e) {

                }

            }
        }

        //*************************************支付信息start**************************************************//
        orderPayAccountList = new ArrayList<>();
        orderPayAccountIterator = inOrderApply.getOrderPayAccountList().iterator();
        while (orderPayAccountIterator.hasNext()) {
            OrderPayAccount orderPayAccount = orderPayAccountIterator.next();
            orderPayAccount.setId(null);
            orderPayAccount.setOrderId(inOrderApply.getId());
            orderPayAccount.setPrice(inOrderApply.getPrice());
            orderPayAccountList.add(orderPayAccount);
        }
        if (orderPayAccountList.size() > 0) {
            iOrderPayAccountService.saveBatch(orderPayAccountList, orderPayAccountList.size());
        }

        inOrderApply.setYearPart(yearPart);
        inOrderApply.setQuarterNum(quarterNum);
        inOrderApply.setTradeContent(tradeContent.toString());
        inOrderApply.setYearClassId(yearClassId);
        if (subjectsId != null) {
            inOrderApply.setSubjectsIdStr(subjectsId.toString());
        }
        orderApplyMapper.updateById(inOrderApply);
        //*************************************支付信息end**************************************************//

        //****************************************报名信息详情 end***********************************//

        //添加智能课或者刷题班
        try {
            Integer lessonType = 1;//精品课
            //转科
            iOrderDetailService.addOrderApply(yearPart, quarterNum, orderTransfer.getInSchoolId(), subjectsId, lessonType, orderApply.getStudentId());

        } catch (Exception e) {
        }

        return true;
    }

    /**
     * 转名额（除了学生可以变，其他都不能变）
     *
     * @param orderApply
     * @return
     * @throws ParseException
     */
    @Transactional
    public boolean transferStudentSave(OrderApply orderApply) throws ParseException {
        Long orderNo = idWorker.nextId();

        OrderApply inOrderApply = (OrderApply) orderApply.clone();//转入（报名）名额用的
        inOrderApply.setOrderNo(orderNo.toString());
        inOrderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER_STUDENT);//退费和转名额两个都设置为一样的状态

        OrderApply returnOrderApply = (OrderApply) orderApply.clone();//转出（退费）名额用的
        returnOrderApply.setOrderNo(orderNo.toString());
        returnOrderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER_STUDENT);//退费和转名额两个都设置为一样的状态

        Integer orderType = returnOrderApply.getOrderType().getKey();
        StringBuilder tradeContent = new StringBuilder();//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元
        OrderTransfer orderTransfer = returnOrderApply.getOrderTransfer();

        if (!orderTransfer.getOutSchoolId().equals(orderTransfer.getInSchoolId())) {
            // 转名额要同校区才可以
            throw new CommonException(ResultCode.SCHOOL_IN_EQUAL);
        }

        Integer outYearPart = 0;
        Integer outQuarterNum = 0;
        Long outCourseId = 0L;//转出课程
        Integer outYearClassId = 0;//转出年级

        Long outSchoolId = 0L;
        Long outStudentId = 0L;
        Long inSchoolId = 0L;

        //****************************************退费信息详情 start***********************************//
        Integer yearClassId = null;
        Iterator<OrderDetail> orderDetailIteratorTurn = inOrderApply.getOrderDetailList().iterator();
        while (orderDetailIteratorTurn.hasNext()) {
            OrderDetail orderDetail = orderDetailIteratorTurn.next();
            Course course = iCourseService.getById(orderDetail.getCourseId());
            yearClassId = course.getYearClassId().getKey();
        }

        Iterator<OrderTransferDetail> orderTransferDetailIterator1 = returnOrderApply.getOrderTransferDetailList().iterator();
        while (orderTransferDetailIterator1.hasNext()) {
            OrderTransferDetail orderTransferDetail = orderTransferDetailIterator1.next();
            OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
            outYearClassId = orderDetail.getYearClassId();
        }

        if (orderType == Code.ORDER_TYPE_TRANSFERSTUDENT) {
            returnOrderApply.setCostType(2);//1收入，2支出
            returnOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
            returnOrderApply.setSchoolId(orderTransfer.getOutSchoolId());//所属校区
            returnOrderApply.setHandleSchoolId(orderTransfer.getOutSchoolId());
            returnOrderApply.setPrice(orderTransfer.getOutPrice());//设置退费金额
            returnOrderApply.setSolidPrice(orderTransfer.getOutPrice());//实收金额
            returnOrderApply.setSubjectsIdStr(orderTransfer.getOutSubjectsId());// 设置退费科目
//            returnOrderApply.setStudentId(orderTransfer.getOutStudentId());// 设置退费学员
            returnOrderApply.setStudentId(returnOrderApply.getStudentId());// 设置退费学员
            returnOrderApply.setYearClassId(outYearClassId);
            orderApplyMapper.insert(returnOrderApply);

            StringBuilder outCourseNames = new StringBuilder();
            Iterator<OrderTransferDetail> orderTransferDetailIterator = returnOrderApply.getOrderTransferDetailList().iterator();
            while (orderTransferDetailIterator.hasNext()) {
                OrderTransferDetail orderTransferDetail = orderTransferDetailIterator.next();
                orderTransferDetail.setOrderType(returnOrderApply.getOrderType());
                orderTransferDetail.setOrderId(returnOrderApply.getId());//设置对应的新订单id

                if (!orderTransferDetail.getOutHouse().equals(0)) {
                    //退费
                    OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                    Course outCourse = iCourseService.getById(orderDetail.getCourseId());
                    if (outCourse != null) {
                        outCourseId = outCourse.getId();
                        outCourseNames.append(outCourse.getName()).append(",");
                        outQuarterNum = outCourse.getQuarterNum();
                    }

                    outYearPart = orderDetail.getYearPart();

                    if (orderDetail != null) {
                        OrderDetail newOrderDetail = new OrderDetail();
                        newOrderDetail.setId(orderDetail.getId());

                        Integer outCourseHouse = orderTransferDetail.getOutHouse();
                        Integer courseHouse = orderDetail.getResidueCourseCount() - outCourseHouse;//剩余课时
                        //退费课时不能大于剩余课时
                        if (courseHouse < 0) {
                            throw new CommonException(ResultCode.REFUND_COURSE_BIG);
                        } else if (courseHouse == 0) {
                            try {
                                // 记上课表里使用课时为0，就把排班删除，如果记上课表里使用不为0，如果排班里is_last为1的排班使用课时为0，就删除这条排班，把使用课时大于0的最后一条排班is_last设置为1
                                QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
                                recordCourseQueryWrapper.eq("student_id", orderApply.getStudentId());
                                recordCourseQueryWrapper.eq("year_part", outYearPart);
                                recordCourseQueryWrapper.eq("quarter", outQuarterNum);
                                recordCourseQueryWrapper.eq("subjects_id", returnOrderApply.getSubjectsIdStr());
                                recordCourseQueryWrapper.eq("lesson_type", 1);
                                recordCourseQueryWrapper.eq("status", 1);
                                Long recordCourseCount = iRecordCourseService.count(recordCourseQueryWrapper);

                                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                                studentGradeQueryWrapper.eq("student_id", orderApply.getStudentId());
                                studentGradeQueryWrapper.eq("year_part", outYearPart);
                                studentGradeQueryWrapper.eq("quarter_num", outQuarterNum);
                                studentGradeQueryWrapper.eq("lesson_type", 1);
                                studentGradeQueryWrapper.eq("subjects_id", returnOrderApply.getSubjectsIdStr());
//                            studentGradeQueryWrapper.eq("status", 1);
//                            studentGradeQueryWrapper.in("reading_status", 0, 1);
                                studentGradeQueryWrapper.eq("deleted", 0);
                                Long studentGradeCount = iStudentGradeService.count(studentGradeQueryWrapper);

                                if (studentGradeCount == 1) {
                                    studentGradeQueryWrapper.eq("is_last", 1);
                                    StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                                    if (studentGrade != null) {
                                        if (recordCourseCount == 0) {
                                            // 删除排班数据
                                            iStudentGradeService.removeById(studentGrade);
                                        } else {
                                            //把所在班级设置为转名额退费状态
                                            studentGrade.setReadingStatus(ReadingStatusEnum.RETREAT);
                                            studentGrade.setStatus(StatusStudentGradeEnum.TURNSTUDENT);
                                            iStudentGradeService.updateById(studentGrade);
                                        }
                                    }
                                } else if (studentGradeCount > 1) {
                                    List<StudentGrade> studentGrades = iStudentGradeService.list(studentGradeQueryWrapper);
                                    for (StudentGrade studentGrade : studentGrades) {
                                        if (studentGrade.getUseCourseCount() == 0) {
                                            iStudentGradeService.removeById(studentGrade);
                                        } else if (studentGrade.getUseCourseCount() > 0) {
                                            //更新为最后一条
                                            QueryWrapper<StudentGrade> studentGradeQueryWrapperNew = new QueryWrapper<>();
                                            studentGradeQueryWrapperNew.eq("year_part", studentGrade.getYearPart());
                                            studentGradeQueryWrapperNew.eq("quarter_num", studentGrade.getQuarterNum());
                                            studentGradeQueryWrapperNew.eq("student_id", studentGrade.getStudentId());
                                            studentGradeQueryWrapperNew.ne("status", 3);
                                            studentGradeQueryWrapperNew.eq("subjects_id", studentGrade.getSubjectsId());
                                            studentGradeQueryWrapperNew.eq("lesson_type", studentGrade.getLessonType());
                                            studentGradeQueryWrapperNew.orderByDesc("id");
                                            List<StudentGrade> studentGradeListNew = iStudentGradeService.list(studentGradeQueryWrapperNew);
                                            Integer i = 0;
                                            for (StudentGrade studentGradeNew : studentGradeListNew) {
                                                if (i == 0) {
                                                    studentGradeNew.setIsLast(1);
                                                    studentGradeNew.setReadingStatus(ReadingStatusEnum.RETREAT);// 调整为退费
                                                    studentGradeNew.setStatus(StatusStudentGradeEnum.TURNSTUDENT);// 从调班转出调整为转名额
                                                } else {
                                                    studentGradeNew.setIsLast(0);
                                                }
                                                iStudentGradeService.updateById(studentGradeNew);
                                                i++;
                                            }
                                            studentGradeQueryWrapperNew.clear();
                                        }
                                    }
                                }

                                // 退费删除智能课、刷题班的排班数据
                                QueryWrapper<StudentGrade> studentGradeQueryWrapper2 = new QueryWrapper<>();
                                studentGradeQueryWrapper2.eq("student_id", orderApply.getStudentId());
                                studentGradeQueryWrapper2.eq("year_part", outYearPart);
                                studentGradeQueryWrapper2.eq("quarter_num", outQuarterNum);
                                studentGradeQueryWrapper2.ne("lesson_type", 1);
                                studentGradeQueryWrapper2.eq("subjects_id", returnOrderApply.getSubjectsIdStr());
                                iStudentGradeService.remove(studentGradeQueryWrapper2);

                                List<Long> ratePayIds = iRatePayService.getIdsByUseCourseCount(orderApply.getStudentId(), Long.parseLong(returnOrderApply.getSubjectsIdStr()), outYearPart, outQuarterNum);
                                for (Long id : ratePayIds) {
                                    iRatePayService.removeById(id);
                                }

                            } catch (Exception ex) {
                                System.err.println(ex.getMessage());
                            }

                            //剩余课时为0，表示全部退出
                            newOrderDetail.setReadingStatus(ReadingStatusEnum.RETREAT);
                            //把所在班级设置为转校退费状态
//                            UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
//                            studentGradeUpdateWrapper.set("reading_status", ReadingStatusEnum.RETREAT.getKey());//设置为退费
//                            studentGradeUpdateWrapper.set("status", 6);//1正常,2（转课）调班转出，3订单作废，4（转校）转出，5（转科）转出，6（转名额）转出
//                            studentGradeUpdateWrapper.eq("order_detail_id", orderDetail.getId());
//                            studentGradeUpdateWrapper.eq("student_id", orderDetail.getStudentId());
//                            studentGradeUpdateWrapper.eq("school_id", orderDetail.getSchoolId());
//                            studentGradeUpdateWrapper.eq("subjects_id", orderDetail.getSubjectsId());
//                            studentGradeUpdateWrapper.eq("year_part", orderDetail.getYearPart());
//                            studentGradeUpdateWrapper.eq("quarter_num", orderDetail.getQuarterNum());
//                            iStudentGradeService.update(studentGradeUpdateWrapper);
                        }

                        //剩余课时
                        newOrderDetail.setResidueCourseCount(courseHouse);
                        BigDecimal outPrice = orderDetail.getTurnOutPrice();
                        if (outPrice == null) {
                            outPrice = BigDecimal.ZERO;
                        }
                        //转校累计退出金额
                        BigDecimal allOutPrice = outPrice.add(orderTransferDetail.getOutPrice());
                        newOrderDetail.setTurnOutPrice(allOutPrice);
                        newOrderDetail.setTurnOutHouse(orderDetail.getTurnOutHouse() + orderTransferDetail.getOutHouse());//累计退出课时
                        //设置剩余金额
                        BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                        residuePrice = residuePrice.subtract(orderTransferDetail.getOutPrice());
                        newOrderDetail.setResiduePrice(residuePrice);
                        orderDetailMapper.updateById(newOrderDetail);
                    } else {
                        throw new CommonException(ResultCode.REFUND_COURSE_NOT);
                    }
                    iOrderTransferDetailService.save(orderTransferDetail);
                }
            }
            if (outCourseNames.length() > 0) {
                outCourseNames.deleteCharAt(outCourseNames.length() - 1);
            }
            //转名额
            if ((orderType == Code.ORDER_TYPE_TRANSFERSTUDENT) && orderTransfer != null) {
                orderTransfer.setOrderId(returnOrderApply.getId());
                iOrderTransferService.save(orderTransfer);
                tradeContent.append("转名额退费：").append(outCourseNames.toString()).append("退").append(orderTransfer.getOutHouse()).append("课次，应退学费").append(orderTransfer.getOutPrice()).append("元");
            }
            returnOrderApply.setYearPart(outYearPart);
            returnOrderApply.setQuarterNum(outQuarterNum);
            returnOrderApply.setTradeContent(tradeContent.toString());
            int[] randMath = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
            Integer randReceiptNo = CommonUtil.getNotSimple(randMath, 7);
            returnOrderApply.setReceiptNo(randReceiptNo.toString());
            orderApplyMapper.updateById(returnOrderApply);

            try {
                // 获取最后一次上课记录的老师
                RecordCourse recordCourse = iRecordCourseService.getRecordCourseByLastThreeQuarter(outYearPart, outQuarterNum, 1, orderApply.getStudentId(), returnOrderApply.getSubjectsIdStr());

                if (recordCourse != null) {
                    // 保存上课老师到表中
                    OrderReturnTeacher orderReturnTeacher = new OrderReturnTeacher();
                    orderReturnTeacher.setOrderId(returnOrderApply.getId());
                    orderReturnTeacher.setTeacherId(recordCourse.getOldTeacherId());
                    iOrderReturnTeacherService.save(orderReturnTeacher);
                }

            } catch (Exception ex) {
                System.err.println(ex.getMessage());
            }

        }

        //*************************************支付信息start**************************************************//
        List<OrderPayAccount> orderPayAccountList = new ArrayList<>();
        Iterator<OrderPayAccount> orderPayAccountIterator = returnOrderApply.getOrderPayAccountList().iterator();
        while (orderPayAccountIterator.hasNext()) {
            OrderPayAccount orderPayAccount = orderPayAccountIterator.next();
            orderPayAccount.setOrderId(returnOrderApply.getId());
            orderPayAccount.setPrice(orderTransfer.getOutPrice());
            orderPayAccountList.add(orderPayAccount);
        }
        if (orderPayAccountList.size() > 0) {
            iOrderPayAccountService.saveBatch(orderPayAccountList, orderPayAccountList.size());
        }
        //*************************************支付信息end**************************************************//


        //****************************************退费信息详情 end***********************************//

        //*************************************订单详情start**************************************************//
        Long inGradeId = null;
        Integer inCourseHosue = 0;

        tradeContent = new StringBuilder();
        Integer yearPart = 0;
        Integer quarterNum = 0;
        Long subjectsId = 0L;
        if (orderType == Code.ORDER_TYPE_TRANSFERSTUDENT) {
            inOrderApply.setReceiptNo(orderApply.getReceiptNo());
            inOrderApply.setCostType(1);//1收入，2支出
            inOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER_STUDENT);
            inOrderApply.setSchoolId(orderTransfer.getInSchoolId());//所属校区
            inOrderApply.setStudentId(orderTransfer.getInStudentId());// 设置转给的学员
            orderApplyMapper.insert(inOrderApply);

            List<StudentGrade> studentGradeList = new ArrayList<>();

            //支付详情
            Iterator<OrderDetail> orderDetailIterator = inOrderApply.getOrderDetailList().iterator();
            while (orderDetailIterator.hasNext()) {

                if (orderType == Code.ORDER_TYPE_TRANSFERSTUDENT) {
                    if (!tradeContent.toString().equals("")) {
                        tradeContent.append("</br>");
                    } else {
                        tradeContent.append("转名额报名：");
                    }
                }

                OrderDetail orderDetail = orderDetailIterator.next();
                inCourseHosue = orderDetail.getAllCourseCount();
                orderDetail.setHandleDate(inOrderApply.getHandleDate());
                orderDetail.setOrderType(inOrderApply.getOrderType());
                orderDetail.setId(idWorker.nextId());
                orderDetail.setStudentId(orderTransfer.getInStudentId());// 设置转给的学员
                orderDetail.setUseCourseCount(0);
                orderDetail.setAllCourseCount(orderDetail.getAllCourseCount());//总课时
                orderDetail.setResidueCourseCount(orderDetail.getAllCourseCount());//剩余课时
                orderDetail.setResiduePrice(orderDetail.getSolidPrice());//优惠金额
                Course course = iCourseService.getById(orderDetail.getCourseId());
                subjectsId = course.getSubjectsId();
                orderDetail.setCourseName(course.getName());
                orderDetail.setSubjectsId(course.getSubjectsId());
                yearClassId = course.getYearClassId().getKey();
                orderDetail.setLessonType(course.getLessonType());//课程类型
                inOrderApply.setLessonType(course.getLessonType());
                //设置报读的季度
                orderDetail.setQuarterNum(course.getQuarterNum());
                tradeContent.append(course.getName()).append(",");
                //添加当前报读的续班信息
                Integer year_part = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份
                orderDetail.setYearPart(year_part);
                orderDetail.setYearClassId(course.getYearClassId().getKey());
                yearPart = year_part;
                quarterNum = course.getQuarterNum();
                //年份与季度
                orderDetail.setYearAndQuarter(Integer.parseInt(year_part + "" + course.getQuarterNum()));
                Grade grade = null;

                if (orderDetail.getGradeId() != null) {
                    //分班
                    StudentGrade studentGrade = new StudentGrade();
                    studentGrade.setOrderDetailId(orderDetail.getId());
                    studentGrade.setStudentId(inOrderApply.getStudentId());
                    studentGrade.setSubjectsId(course.getSubjectsId());//科目id
                    studentGrade.setGradeId(orderDetail.getGradeId());
                    studentGrade.setCourseId(orderDetail.getCourseId());
                    studentGrade.setYearPart(year_part);
                    studentGrade.setQuarterNum(course.getQuarterNum());
                    grade = iGradeService.getById(orderDetail.getGradeId());
                    if (grade != null) {
                        inGradeId = grade.getId();
                        orderDetail.setGradeName(grade.getName());
                        orderDetail.setCourseHouse(grade.getStuDeductHour());
                        studentGrade.setSchoolId(grade.getSchoolId());

                        //添加到班级
                        iStudentGradeService.addData(orderDetail.getId(), grade.getSchoolId(), orderApply.getStudentId(), grade.getId(), course.getId(), course.getSubjectsId(), year_part, course.getQuarterNum(), orderDetail.getAllCourseCount(), course.getYearClassId().getKey(), grade.getLessonType(), grade.getCourseTypeId(), 1);
                    }
                    studentGradeList.add(studentGrade);
                }

                tradeContent.append(orderDetail.getPrice());

                if (orderDetail.getCoursePriceId() != null) {
                    CoursePricing coursePricing = iCoursePricingService.getById(orderDetail.getCoursePriceId());
                    if (coursePricing != null) {
                        tradeContent.append("(").append(coursePricing.getCountUnit()).append(")*").append(orderDetail.getCount()).append("=").append(orderDetail.getPrice()).append("元");
                        orderDetail.setCoursePriceName(coursePricing.getCount() + coursePricing.getCountUnit() + "=" + coursePricing.getAllPrice() + "元");

                        //保存到订单支付价格表
                        OrderCoursePricing orderCoursePricing = new OrderCoursePricing();
                        orderCoursePricing.setId(orderDetail.getId());
                        orderCoursePricing.setPrice(coursePricing.getPrice());
                        orderCoursePricing.setCount(coursePricing.getCount());
                        orderCoursePricing.setCountUnit(coursePricing.getCountUnit());
                        orderCoursePricing.setUnitPrice(coursePricing.getUnitPrice());
                        orderCoursePricing.setChargeMode(coursePricing.getChargeMode());
                        orderCoursePricing.setServePrice(coursePricing.getServePrice());
                        orderCoursePricing.setMaterialsPrice(coursePricing.getMaterialsPrice());
                        orderCoursePricing.setAllPrice(coursePricing.getAllPrice());
                        iOrderCoursePricingService.saveOrUpdate(orderCoursePricing);
                    }
                }
                orderDetail.setOrderId(inOrderApply.getId());

                Long studentId = orderApply.getStudentId();

                UpdateWrapper<Student> studentUpdateWrapper = new UpdateWrapper<>();
                studentUpdateWrapper.eq("id", studentId).set("school_id", orderDetail.getSchoolId());
                iStudentService.update(null, studentUpdateWrapper);
                iStudentSchoolService.addOrUpdateData(studentId, orderDetail.getSchoolId());

                QueryWrapper<StudentSchool> studentSchoolQueryWrapper = new QueryWrapper<StudentSchool>();
                studentSchoolQueryWrapper.eq("school_id", orderDetail.getSchoolId());
                studentSchoolQueryWrapper.eq("student_id", orderDetail.getStudentId());
                Long studentSchoolCount = iStudentSchoolService.count(studentSchoolQueryWrapper);
                if (studentSchoolCount.equals(0L)) {
                    StudentSchool studentSchool = new StudentSchool();
                    studentSchool.setId(idWorker.nextId());
                    studentSchool.setSchoolId(orderDetail.getSchoolId());
                    studentSchool.setStudentId(orderDetail.getStudentId());
                    iStudentSchoolService.save(studentSchool);
                }
                iOrderDetailService.save(orderDetail);

                iRenewDataService.transferSchoolUpdate(orderApply.getStudentId(), orderTransfer.getOutSchoolId(), outYearPart, orderTransfer.getInSchoolId(), outCourseId, orderTransfer.getInGradeId(), inGradeId, inCourseHosue, orderDetail.getId());

                outStudentId = orderApply.getStudentId();
                outSchoolId = orderTransfer.getOutSchoolId();
                inSchoolId = orderTransfer.getOutSchoolId();

                QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
                studentFaceDataQueryWrapper.eq("school_id", inSchoolId);
                studentFaceDataQueryWrapper.eq("student_id", outStudentId);
                Long count = iStudentFaceDataService.count(studentFaceDataQueryWrapper);
                if (count == 0) {
                    studentFaceDataQueryWrapper.clear();
                    studentFaceDataQueryWrapper.eq("school_id", outSchoolId);
                    studentFaceDataQueryWrapper.eq("student_id", outStudentId);
                    List<StudentFaceData> studentFaceDataList = iStudentFaceDataService.list(studentFaceDataQueryWrapper);
                    for (StudentFaceData studentFaceData : studentFaceDataList) {
                        StudentFaceData studentFaceDataNew = new StudentFaceData();
                        BeanUtils.copyProperties(studentFaceData, studentFaceDataNew);
                        studentFaceDataNew.setId(idWorker.nextId());
                        studentFaceDataNew.setSchoolId(inSchoolId);
                        studentFaceDataNew.setEntityId(0L);
                        studentFaceDataNew.setFaceId("");
                        studentFaceDataNew.setUpdateLevel(1);
                        iStudentFaceDataService.save(studentFaceData);
                    }
                }
                //更新预分班，还没有添加订单id的
                iStudentGradeService.updateOrderDetailId(orderDetail.getYearPart(), orderDetail.getQuarterNum(), orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getId());

                try {
                    StudentGrade studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getYearPart(), orderDetail.getQuarterNum(), course.getLessonType());
                    Grade gradeOld = null;
                    if (studentGrade != null) {
                        gradeOld = iGradeService.getById(studentGrade.getGradeId());
                    }
                    if (gradeOld != null) {
                        RatePay ratePay = new RatePay();
                        ratePay.setSchoolId(inSchoolId);
                        ratePay.setTeacherId(gradeOld.getTeacherId());
                        ratePay.setStudentId(orderDetail.getStudentId());
                        ratePay.setSubjectsId(orderDetail.getSubjectsId());
                        ratePay.setGradeId(gradeOld.getId());
                        ratePay.setYearPart(orderDetail.getYearPart());
                        ratePay.setQuarterNum(orderDetail.getQuarterNum());
                        ratePay.setYearClassId(orderDetail.getYearClassId());
                        ratePay.setOrderId(orderDetail.getOrderId());
                        ratePay.setOrderDetailId(orderDetail.getId());
                        ratePay.setId(idWorker.nextId());
                        ratePay.setNum(1);
                        ratePay.setAddDate(LocalDate.now());
                        ratePay.setCreatedAt(LocalDateTime.now().withNano(0));
                        ratePay.setStatus(1);//如果是lkl创建订单，这里先设置为2，支付成功后，再用回调方法调整为1
                        Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getYearAndQuarter(), course.getLessonType());
                        if (residueCourseCount >= 45) {
                            Integer rayNum = residueCourseCount / 45;
                            ratePay.setNum(rayNum);
                            iRatePayService.save(ratePay);
                        }
                    }

                } catch (Exception e) {

                }

            }
        }

        //*************************************支付信息start**************************************************//
        orderPayAccountList = new ArrayList<>();
        orderPayAccountIterator = inOrderApply.getOrderPayAccountList().iterator();
        while (orderPayAccountIterator.hasNext()) {
            OrderPayAccount orderPayAccount = orderPayAccountIterator.next();
            orderPayAccount.setId(null);
            orderPayAccount.setOrderId(inOrderApply.getId());
            orderPayAccount.setPrice(inOrderApply.getPrice());
            orderPayAccountList.add(orderPayAccount);
        }
        if (orderPayAccountList.size() > 0) {
            iOrderPayAccountService.saveBatch(orderPayAccountList, orderPayAccountList.size());
        }

        inOrderApply.setYearPart(yearPart);
        inOrderApply.setQuarterNum(quarterNum);
        inOrderApply.setTradeContent(tradeContent.toString());
        inOrderApply.setYearClassId(yearClassId);
        if (subjectsId != null) {
            inOrderApply.setSubjectsIdStr(subjectsId.toString());
        }
        orderApplyMapper.updateById(inOrderApply);
        //*************************************支付信息end**************************************************//

        //****************************************报名信息详情 end***********************************//

        //添加智能课或者刷题班
        try {
            Integer lessonType = 1;//精品课
            //转名额
            iOrderDetailService.addOrderApply(yearPart, quarterNum, orderTransfer.getInSchoolId(), subjectsId, lessonType, orderApply.getStudentId());
        } catch (Exception e) {

        }

        return true;
    }

    private OrderApply getOutSchoolDetail(Long outSchoolId, Long inSchoolId, Long studentId, Long subjectsId, Integer lessontType) {

        OrderApply orderApply = new OrderApply();
        Quarter quarterNow = iQuarterService.getNowQuarter();//当前学期

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("student_id", studentId);
        orderDetailQueryWrapper.eq("school_id", outSchoolId);
        orderDetailQueryWrapper.eq("subjects_id", subjectsId);
        orderDetailQueryWrapper.gt("residue_course_count", 0);
        orderDetailQueryWrapper.eq("year_part", quarterNow.getYearPart());
        orderDetailQueryWrapper.eq("quarter_num", quarterNow.getNum());
        orderDetailQueryWrapper.eq("lesson_type", lessontType);

        //orderDetailQueryWrapper.eq("version",0);
        orderDetailQueryWrapper.ne("status", 2);
        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);

        OrderTransfer orderTransfer = new OrderTransfer();
        orderTransfer.setOutSchoolId(outSchoolId);
        orderTransfer.setOutGradeId(subjectsId);
        orderTransfer.setInSchoolId(inSchoolId);
        orderTransfer.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL.getKey());
        orderTransfer.setOutType(1);
        orderTransfer.setVersion(2);

        OrderTransferDetail orderTransferDetail = null;
        List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();

        Integer outHouse = 0;
        BigDecimal outPrice = new BigDecimal(0);


        Course courseOld = null;
        Integer quarterNum = 0;
        for (OrderDetail orderDetail : orderDetailList) {
            courseOld = iCourseService.getById(orderDetail.getCourseId());
            quarterNum = orderDetail.getQuarterNum();
            orderTransferDetail = new OrderTransferDetail();
            orderTransferDetail.setOldOrderId(orderDetail.getOrderId());
            orderTransferDetail.setOldOrderDetailId(orderDetail.getId());
            orderTransferDetail.setOutHouse(orderDetail.getResidueCourseCount());//剩余课程
            orderTransferDetail.setOutPrice(orderDetail.getResiduePrice());//剩余金额
            orderTransferDetail.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);
            orderTransferDetailList.add(orderTransferDetail);

            outHouse += orderDetail.getResidueCourseCount();
            BigDecimal resPrice = orderDetail.getResiduePrice();
            outPrice = outPrice.add(resPrice);

            orderApply.setYearClassId(courseOld.getYearClassId().getKey());
            orderApply.setSubjectsIdStr(courseOld.getSubjectsId().toString());
        }
        orderTransfer.setOutHouse(outHouse);
        orderTransfer.setOutPrice(outPrice);

        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.eq("subjects_id", subjectsId);
        courseQueryWrapper.eq("year_class_id", courseOld.getYearClassId());//年级，
        courseQueryWrapper.eq("quarter_num", quarterNum);//顺延到当前学期
        courseQueryWrapper.eq("status", 1);
        courseQueryWrapper.and(i -> i.eq("opening_school_type", 1).or().inSql("id", "select for_id from appoint_school where type = 1 and school_id= " + inSchoolId + " "));

        courseQueryWrapper.last("limit 1");
        //System.out.println("studentId:" + studentId);
        Course course = iCourseService.getOne(courseQueryWrapper);
        if (course == null) {
            //System.out.println("课程为空");
            return null;
        }
        orderTransfer.setInGradeId(course.getId());//转入课程id

        QueryWrapper<CoursePricing> coursePricingQueryWrapper = new QueryWrapper<>();

        if (course.getOpeningSchoolType().getKey().equals(1)) {
            //select id from course_price_school where course_id = and school_id =
            coursePricingQueryWrapper.inSql("price_school_id", "select id from course_price_school where course_id = " + course.getId() + " and school_id =0 and deleted=0");
        } else {
            coursePricingQueryWrapper.inSql("price_school_id", "select id from course_price_school where course_id = " + course.getId() + " and school_id =" + inSchoolId + " and deleted=0");

        }

        if ((orderTransfer.getOutHouse() % 45) == 0) {
            coursePricingQueryWrapper.eq("count", 45);
        } else {
            coursePricingQueryWrapper.eq("count", 3);
        }
        //coursePricingQueryWrapper.eq("status",1);
        coursePricingQueryWrapper.last("limit 1");


        CoursePricing coursePricing = iCoursePricingService.getOne(coursePricingQueryWrapper);

        if (coursePricing == null) {
            //System.out.println("没有找到课程价格数据");
            return null;
        }

        int[] randMath = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
        Integer randReceiptNo = CommonUtil.getNotSimple(randMath, 7);
        orderApply.setReceiptNo(randReceiptNo.toString());

        BigDecimal unitPrice = coursePricing.getUnitPrice();

        LocalDate nowDate = LocalDate.now();


        //订单详情实收金额
        BigDecimal residuePrice = orderTransfer.getOutPrice();

        //课程应收
        //BigDecimal price = new BigDecimal(orderTransfer.getOutHouse()).divide(new BigDecimal(3),BigDecimal.ROUND_UP).multiply(unitPrice);
        BigDecimal price = residuePrice;

        //订单实收
        BigDecimal solidPrice = residuePrice;//new BigDecimal(0);
        BigDecimal disPrice = new BigDecimal(0);//price.subtract(residuePrice)

        BigDecimal orderPrice = residuePrice;//price.subtract(residuePrice).subtract(disPrice);

        orderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);
        orderApply.setPrice(orderPrice);
        orderApply.setSolidPrice(solidPrice);
        if (disPrice.compareTo(BigDecimal.ZERO) > 0) {
            orderApply.setDiscountsDate(nowDate);
        }
        orderApply.setDisPrice(disPrice);
        orderApply.setStudentId(studentId);
        orderApply.setHandleSchoolId(inSchoolId);
        orderApply.setHandleDate(nowDate);
        //orderApply.setTransferPrice(residuePrice);//转课抵扣金额

        OrderDetail orderDetailNew = new OrderDetail();
        orderDetailNew.setSchoolId(inSchoolId);
        orderDetailNew.setCourseId(course.getId());
        orderDetailNew.setYearClassId(course.getYearClassId().getKey());
        orderDetailNew.setCoursePriceId(coursePricing.getId());
        orderDetailNew.setCount(outHouse / coursePricing.getCount());
        orderDetailNew.setAllCourseCount(outHouse);
        orderDetailNew.setPrice(price);
        orderDetailNew.setSolidPrice(residuePrice);
        orderDetailNew.setDiscountsPrice(disPrice);
        if (disPrice.compareTo(BigDecimal.ZERO) > 0) {
            orderDetailNew.setDiscountsDate(nowDate);
        }

        List<OrderDetail> orderDetailListNew = new ArrayList<>();
        orderDetailListNew.add(orderDetailNew);

        List<OrderPayAccount> orderPayAccountList = new ArrayList<>();
        OrderPayAccount orderPayAccount = new OrderPayAccount();
        orderPayAccount.setPrice(solidPrice);
        orderPayAccount.setAccounType(1);
        orderPayAccount.setAccountTypeName("现金");
        orderPayAccountList.add(orderPayAccount);

        orderApply.setOrderTransfer(orderTransfer);//添加转课信息
        orderApply.setOrderTransferDetailList(orderTransferDetailList);
        orderApply.setOrderDetailList(orderDetailListNew);//添加转课详情
        orderApply.setOrderPayAccountList(orderPayAccountList);

        return orderApply;
    }

    //public void

    public boolean updateTo(OrderApply orderApply) {
        this.updateById(orderApply);
        //System.out.print("insertId:"+orderApply.getId());
        List<OrderDetail> orderDetailList = new ArrayList<>();

        List<OrderPayAccount> orderPayAccountList = new ArrayList<>();
        List<OrderPayAccount> updateOrderPayAccountList = new ArrayList<>();

        Iterator<OrderDetail> orderDetailIterator = orderApply.getOrderDetailList().iterator();
        while (orderDetailIterator.hasNext()) {
            OrderDetail orderDetail = orderDetailIterator.next();
            orderDetail.setResidueCourseCount(orderDetail.getAllCourseCount() - orderDetail.getUseCourseCount());
            orderDetail.setOrderType(orderApply.getOrderType());
            if (orderDetail.getCoursePriceId() != null) {
                CoursePricing coursePricing = iCoursePricingService.getById(orderDetail.getCoursePriceId());
                if (coursePricing != null) {
                    orderDetail.setCoursePriceName(coursePricing.getCount() + coursePricing.getCountUnit() + "=" + coursePricing.getAllPrice() + "元");
                }
            }
            if (orderDetail.getId() != null) {
                orderDetailList.add(orderDetail);
            }

        }

        Iterator<OrderPayAccount> orderPayAccountIterator = orderApply.getOrderPayAccountList().iterator();
        while (orderDetailIterator.hasNext()) {
            OrderPayAccount orderPayAccount = new OrderPayAccount();
            if (orderPayAccount.getId() != null && orderPayAccount.getId() != 0) {
                updateOrderPayAccountList.add(orderPayAccount);
            } else {
                orderPayAccountList.add(orderPayAccount);
            }
        }

        if (orderDetailList.size() > 0) {
            iOrderDetailService.updateBatchById(orderDetailList, orderDetailList.size());
        }
        if (orderPayAccountList.size() > 0) {
            iOrderPayAccountService.saveBatch(orderPayAccountList, orderPayAccountList.size());
        }
        if (updateOrderPayAccountList.size() > 0) {
            iOrderPayAccountService.updateBatchById(updateOrderPayAccountList, updateOrderPayAccountList.size());
        }
        return true;
    }

    public IPage<OrderApply> findAll(IPage<?> page, Wrapper wrapper) {
        IPage<OrderApply> orderApplyIPage = orderApplyMapper.findAll(page, wrapper);
        for (OrderApply orderApply : orderApplyIPage.getRecords()) {
            if (orderApply.getStatus().equals(StatusOrderApplyEnum.TOVOID)) {
                if (!orderApply.getAbolishType().equals(2)) {
                    orderApply.setStatus(StatusOrderApplyEnum.NO);
                }
            }
            BigDecimal discountPrice = orderDetailMapper.getOrderDiscounts(orderApply.getId());
            orderApply.setDiscountsPrice(discountPrice);
        }
        return orderApplyIPage;
    }

    @Override
    public OrderApply getOneForId(Long id) {
        return orderApplyMapper.getOneForId(id);
    }

    public OrderApply getPrintData(Long orderId) {
        OrderApply orderApply = orderApplyMapper.selectById(orderId);
        String yearClassName = "";
        if (orderApply.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_SiGN)) {
            yearClassName = orderDetailMapper.getYearClassNameForOrderId(orderApply.getId());
            List<String> courseNameList = orderDetailMapper.getCourseNameListForOrderId(orderApply.getId());
            StringBuilder courseNameBuilder = new StringBuilder();
            Integer i = 0;
            for (String courseName : courseNameList) {
                courseNameBuilder.append(courseName);
                if (i < (courseNameList.size() - 1)) {
                    courseNameBuilder.append(",");
                }
                i++;
            }
            orderApply.setCourseName(courseNameBuilder.toString());
            QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.eq("order_id", orderApply.getId());
            orderDetailQueryWrapper.groupBy("subjects_id");
            List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);
            List<String> subjectsNames = new ArrayList<>();
            for (OrderDetail orderDetail : orderDetailList) {
                subjectsNames.add(CommonUtil.getSubjectsNameForId(Integer.parseInt(orderDetail.getSubjectsId().toString())));
            }
            if (subjectsNames.size() > 0) {
                orderApply.setSubjectsNames(String.join(",", subjectsNames));
            }

        } else {
            Long oldOrderId = iOrderTransferDetailService.getOldOrderId(orderApply.getId());
            if (oldOrderId != null) {
                yearClassName = orderDetailMapper.getYearClassNameForOrderId(oldOrderId);
            }
        }
        orderApply.setYearClassName(yearClassName);
        BigDecimal discountPrice = orderDetailMapper.getOrderDiscounts(orderApply.getId());
        orderApply.setDiscountsPrice(discountPrice);
        Student student = iStudentService.getById(orderApply.getStudentId());
        orderApply.setStudentName(student.getName());

        return orderApply;

    }


    public List<Map<String, Object>> orderArrears(Wrapper wrapper) {
        return orderApplyMapper.orderArrears(wrapper);
    }


    /**
     * 收支明细
     *
     * @param page
     * @param wrapper
     * @return
     */
    public IPage<OrderApply> expensesAndReceipts(IPage<?> page, Wrapper wrapper) {
        return orderApplyMapper.expensesAndReceipts(page, wrapper);
    }

    public IPage<ResTransaction> transaction(IPage<?> page, Wrapper wrapper) {

        IPage<ResTransaction> iPage = orderApplyMapper.transaction(page, wrapper);
        for (ResTransaction resTransaction : iPage.getRecords()) {
            resTransaction.setSubjectsName(subjectsMapper.getName(resTransaction.getSubjectsId()));
        }

        return iPage;
    }

    public IPage<OrderApply> affirmIncome(IPage<?> page, Wrapper wrapper) {
        IPage<OrderApply> orderApplyIPage = orderApplyMapper.affirmIncome(page, wrapper);
        for (OrderApply orderApply : orderApplyIPage.getRecords()) {
            if (orderApply.getAffirmTypeList().contains(1)) {
                orderApply.setArriveAffirm(ArriveAffirmEnum.CONFIRM);
            }
            if (orderApply.getAffirmTypeList().contains(3)) {
                orderApply.setArriveAffirm(ArriveAffirmEnum.TOVOID);
            }
        }
        return orderApplyIPage;
    }

    /**
     * 校长确认到帐
     *
     * @param id
     * @param adminId 登陆人id
     * @param isSuper 是否超级管理员
     * @return
     */
    @Transactional
    public boolean confirmArrive(Long id, Long adminId, Integer isSuper) {
        OrderApply orderApply = this.getById(id);
        Integer rs = 1;
        if (orderApply == null) {
            throw new CommonException(ResultCode.NOORDER);
        } else {
            if (orderApply.getDisPrice().compareTo(BigDecimal.ZERO) > 0) {
                //优惠先确认
                /*OrderApplyAffirm orderApplyAffirm = iOrderApplyAffirmService.getOneForOrderId(orderApply.getId(),2,1);
                if (orderApplyAffirm == null) {
                    throw new CommonException(ResultCode.DIS_AFIRM);
                }*/
            }
            orderApply.setStatus(StatusOrderApplyEnum.CONFIRM);
            //if (orderApply.getSignType().equals(3)){
            //拉卡拉支付
            //    orderApply.setPayType(1);
            //}
            orderApply.setPayType(1);
            orderApply.setAffirmMode(1);
            //orderApply.setArriveAffirm(ArriveAffirmEnum.CONFIRM);
            //orderApply.setPrincipalDate(LocalDateTime.now());
            this.updateById(orderApply);
            LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId, id).set(OrderDetail::getStatus, StatusOrderApplyEnum.CONFIRM).set(OrderDetail::getPayType, 1);
            orderDetailMapper.update(null, orderDetailLambdaUpdateWrapper);
            iRatePayService.updateStatusForOrderId(orderApply.getId(), 1);//设置缴费率的状态
            iOrderApplyAffirmService.addAffirm(orderApply.getId(), 1, 1, "校长确认", adminId);
            //设置缴费数据状态
            LambdaUpdateWrapper<LklOrder> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(LklOrder::getOutOrderNo, orderApply.getLklOrderNo()).set(LklOrder::getPayType, 1);
            iLklOrderService.update(null, updateWrapper);

        }
        return true;
    }


    /**
     * 财务确认到帐
     *
     * @param id
     * @param adminId
     * @param isSuper
     * @return
     */
    public boolean financeConfirm(Long id, Long adminId, Integer isSuper) {
        OrderApply orderApply = this.getById(id);
        Integer rs = 1;
        if (orderApply == null) {
            throw new CommonException(ResultCode.NOORDER);
        } else {
            OrderApplyAffirm orderApplyAffirm = iOrderApplyAffirmService.getOneForOrderId(orderApply.getId(), 1, 1);
            if (orderApplyAffirm == null) {
                throw new CommonException(ResultCode.SCHOOL_AFIRM);
            }
            orderApply.setArriveAffirm(ArriveAffirmEnum.TOVOID);
            orderApply.setFinanceDate(LocalDateTime.now());
            this.updateById(orderApply);
            LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId, id).set(OrderDetail::getArriveAffirm, ArriveAffirmEnum.TOVOID);
            orderDetailMapper.update(null, orderDetailLambdaUpdateWrapper);
            iOrderApplyAffirmService.addAffirm(orderApply.getId(), 3, 1, "财务确认", adminId);

        }
        return true;
    }

    /**
     * 取消确认
     *
     * @param id
     * @param adminId
     * @param isSuper
     * @return
     */
    public boolean cancelConfirm(Long id, Long adminId, Integer isSuper) {
        OrderApply orderApply = this.getById(id);
        Integer rs = 1;
        if (orderApply == null) {
            throw new CommonException(ResultCode.NOORDER);
        } else {
            if (orderApply.getAffirmMode().equals(2)) {
                //自动确认的不能取消
                throw new CommonException(ResultCode.AUTOAFFIRM_NOT_CANCCEL);
            }
            Integer useHouseCount = orderDetailMapper.getUseHouseForOrderId(orderApply.getId());

            if (useHouseCount > 0) {
                throw new CommonException(ResultCode.NOT_CANCEL_INVALIDATEUSE);
            }
            if (orderApply.getSignType().equals(3)) {
                //拉卡拉支付
                orderApply.setStatus(StatusOrderApplyEnum.TOVOID);//调整为订单作废
                orderApply.setPayType(0);
                LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId, id).set(OrderDetail::getStatus, StatusOrderApplyEnum.TOVOID).set(OrderDetail::getPayType, 0);
                orderDetailMapper.update(null, orderDetailLambdaUpdateWrapper);
                iRatePayService.updateStatusForOrderId(orderApply.getId(), 2);//设置缴费率的状态
                //设置缴费数据状态
                LambdaUpdateWrapper<LklOrder> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(LklOrder::getOutOrderNo, orderApply.getLklOrderNo()).set(LklOrder::getPayType, 0);
                iLklOrderService.update(null, updateWrapper);
            } else {
                orderApply.setStatus(StatusOrderApplyEnum.NO);
            }
            //orderApply.setArriveAffirm(ArriveAffirmEnum.NO);
            this.updateById(orderApply);

            //删除所有确认的数据
            iOrderApplyAffirmService.delAffirmForType(orderApply.getId(), 1);

        }
        return true;
    }


    /**
     * 订单作废
     *
     * @param id
     * @param adminId 登陆人id
     * @param isSuper 是否超级管理员
     * @return
     */
    @Transactional
    public boolean invalidate(Long id, Long adminId, Integer isSuper) {
        OrderApply orderApply = this.getById(id);
        if (orderApply == null) {
            throw new CommonException(ResultCode.NOORDER);
        } else {

            Long useHouseOrderId = orderApply.getId();
            OrderApply orderApplyTurn = null;
            if (orderApply.getApplyType() != null && orderApply.getApplyType().equals(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL)) {
                //更具转校退费单，获取转校单
                orderApplyTurn = orderApplyMapper.getOneForOrderNo(orderApply.getOrderNo(), 5);
                if (orderApplyTurn != null) {
                    useHouseOrderId = orderApplyTurn.getId();
                }
            }
            if (orderApply.getApplyType() != null && orderApply.getApplyType().equals(OrderTypeEnum.ORDER_TYPE_TRANSFER_STUDENT)) {
                //根据转名额退费单，获取转名额单
                orderApplyTurn = orderApplyMapper.getOneForOrderNo(orderApply.getOrderNo(), 8);
                if (orderApplyTurn != null) {
                    useHouseOrderId = orderApplyTurn.getId();
                }
            }
            if (orderApply.getApplyType() != null && orderApply.getApplyType().equals(OrderTypeEnum.ORDER_TYPE_TRANSFER_SUBJECT)) {
                //根据转科目退费单，获取转科目单
                orderApplyTurn = orderApplyMapper.getOneForOrderNo(orderApply.getOrderNo(), 9);
                if (orderApplyTurn != null) {
                    useHouseOrderId = orderApplyTurn.getId();
                }
            }

            Integer useHouseCount = orderDetailMapper.getUseHouseForOrderId(useHouseOrderId);

            if (orderApply.getStatus() == StatusOrderApplyEnum.CONFIRM) {
                throw new CommonException(ResultCode.NOTINVALIDATE);
            } else if (useHouseCount > 0) {
                throw new CommonException(ResultCode.NOTINVALIDATEUSE);
            } else if (orderApply.getAbolishType() == 2) {
                throw new CommonException(ResultCode.SUCCESS);
            }

            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id", id));
            for (OrderDetail orderDetail : orderDetailList) {
                //iRenewClassService.update(null,new LambdaUpdateWrapper<RenewClass>().eq(RenewClass::getOrderDetailId,orderDetail.getId()).set(RenewClass::getStatus,2).set(RenewClass::getOrderStatus,2));
                iRenewDataService.deleteData(orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getYearPart(), orderDetail.getQuarterNum());
                //更新报读班级的状态
                /*LambdaUpdateWrapper<StudentGrade> studentGradeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                studentGradeLambdaUpdateWrapper.eq(StudentGrade::getOrderDetailId,orderDetail.getId()).set(StudentGrade::getStatus,3);
                iStudentGradeService.update(null,studentGradeLambdaUpdateWrapper);*/

                LambdaQueryWrapper<StudentGrade> studentGradeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                studentGradeLambdaQueryWrapper.eq(StudentGrade::getOrderDetailId, orderDetail.getId());
                iStudentGradeService.remove(studentGradeLambdaQueryWrapper);

                iRenewDataService.deleteData(orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getYearPart(), orderDetail.getQuarterNum());

            }

            //订单类型：1报名，2补费，3转课，4退费，5转校
            if (orderApply.getOrderType().getKey() == 1) {
                orderApply.setStatus(StatusOrderApplyEnum.TOVOID);
                orderApply.setAbolishType(2);//作废
                this.updateById(orderApply);
                //更新报读详情的状态
                LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId, id).set(OrderDetail::getStatus, StatusOrderApplyEnum.TOVOID);
                orderDetailMapper.update(null, orderDetailLambdaUpdateWrapper);
            } else if (orderApply.getOrderType().getKey() == 2) {

                orderApply.setStatus(StatusOrderApplyEnum.TOVOID);
                orderApply.setAbolishType(2);//作废
                this.updateById(orderApply);
                LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId, id).set(OrderDetail::getStatus, StatusOrderApplyEnum.TOVOID);
                orderDetailMapper.update(null, orderDetailLambdaUpdateWrapper);
            } else if (orderApply.getOrderType().getKey() == 3) {
                List<OrderTransferDetail> orderTransferDetailList = iOrderTransferDetailService.list(new QueryWrapper<OrderTransferDetail>().eq("order_id", orderApply.getId()));
                for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
                    OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                    orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + orderTransferDetail.getOutHouse());

                    orderDetail.setRollOutHouse(orderDetail.getRollOutHouse() - orderTransferDetail.getOutHouse());//恢复转出课时
                    orderDetail.setRollOutPrice(orderDetail.getRollOutPrice().subtract(orderTransferDetail.getOutPrice()));
                    orderDetail.setReadingStatus(ReadingStatusEnum.IN_READING);

                    BigDecimal outPrice = orderTransferDetail.getOutPrice();
                    BigDecimal residuePrice = orderDetail.getResiduePrice().add(outPrice);
                    if (residuePrice.compareTo(orderDetail.getSolidPrice()) <= 0) {
                        orderDetail.setResiduePrice(residuePrice);
                    } else {
                        orderDetail.setResiduePrice(orderDetail.getResiduePrice().add(orderDetail.getUsePrice()));
                    }
                    iOrderDetailService.updateById(orderDetail);

                    orderTransferDetail.setStatus(2);//设置为作废
                    iOrderTransferDetailService.updateById(orderTransferDetail);
                }

                orderApply.setStatus(StatusOrderApplyEnum.TOVOID);
                this.updateById(orderApply);
                LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId, id).set(OrderDetail::getStatus, StatusOrderApplyEnum.TOVOID);
                orderDetailMapper.update(null, orderDetailLambdaUpdateWrapper);
            } else if (orderApply.getOrderType().getKey() == 4) {
                //退费
                List<OrderTransferDetail> orderTransferDetailList = iOrderTransferDetailService.list(new QueryWrapper<OrderTransferDetail>().eq("order_id", orderApply.getId()));
                for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
                    OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                    orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + orderTransferDetail.getOutHouse());
                    BigDecimal outPrice = orderTransferDetail.getOutPrice();
                    BigDecimal residuePrice = orderDetail.getResiduePrice().add(outPrice);
                    if (residuePrice.compareTo(orderDetail.getSolidPrice()) <= 0) {
                        orderDetail.setResiduePrice(residuePrice);
                    } else {
                        orderDetail.setResiduePrice(orderDetail.getResiduePrice().add(orderDetail.getUsePrice()));
                    }

                    if (orderApply.getApplyType() != null && orderApply.getApplyType().equals(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL)) {
                        //恢复转校转累计转出数据
                        orderDetail.setTurnOutHouse(orderDetail.getTurnOutHouse() - orderTransferDetail.getOutHouse());//恢复转出课时
                        orderDetail.setTurnOutPrice(orderDetail.getTurnOutPrice().subtract(outPrice));
                        orderDetail.setReadingStatus(ReadingStatusEnum.IN_READING);
                        iOrderDetailService.updateById(orderDetail);
                    } else {
                        //恢复退费累计退出数据
                        orderDetail.setOutHouse(orderDetail.getOutHouse() - orderTransferDetail.getOutHouse());//恢复转出课时
                        orderDetail.setOutPrice(orderDetail.getOutPrice().subtract(outPrice));
                        orderDetail.setReadingStatus(ReadingStatusEnum.IN_READING);
                        iOrderDetailService.updateById(orderDetail);
                    }
                    orderTransferDetail.setStatus(2);//设置为作废
                    iOrderTransferDetailService.updateById(orderTransferDetail);
                }
                if (orderApplyTurn != null) {
                    //转校单，要同时作废
                    orderApplyTurn.setStatus(StatusOrderApplyEnum.TOVOID);
                    orderApplyTurn.setAbolishType(2);//作废
                    this.updateById(orderApplyTurn);
                    LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId, orderApplyTurn.getId()).set(OrderDetail::getStatus, StatusOrderApplyEnum.TOVOID);
                    orderDetailMapper.update(null, orderDetailLambdaUpdateWrapper);
                }

                orderApply.setStatus(StatusOrderApplyEnum.TOVOID);
                orderApply.setAbolishType(2);//作废
                this.updateById(orderApply);

            } else if (orderApply.getOrderType().getKey() == 5) {

                OrderApply orderApplyReturn = orderApplyMapper.getOneForOrderNo(orderApply.getOrderNo(), 4);
                if (orderApplyReturn != null) {
                    //转校的恢复数据从退费里恢复
                    List<OrderTransferDetail> orderTransferDetailList = iOrderTransferDetailService.list(new QueryWrapper<OrderTransferDetail>().eq("order_id", orderApplyReturn.getId()));
                    Long outOrderId = null;
                    for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
                        outOrderId = orderTransferDetail.getOldOrderId();
                        OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                        orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + orderTransferDetail.getOutHouse());
                        BigDecimal outPrice = orderTransferDetail.getOutPrice();
                        BigDecimal residuePrice = orderDetail.getResiduePrice().add(outPrice);

                        orderDetail.setTurnOutHouse(orderDetail.getTurnOutHouse() - orderTransferDetail.getOutHouse());//恢复转出课时
                        orderDetail.setTurnOutPrice(orderDetail.getTurnOutPrice().subtract(outPrice));

                        orderDetail.setReadingStatus(ReadingStatusEnum.IN_READING);
                        orderDetail.setResiduePrice(residuePrice);
                        iOrderDetailService.updateById(orderDetail);
                        orderTransferDetail.setStatus(2);//设置为作废
                        iOrderTransferDetailService.updateById(orderTransferDetail);
                    }
                    //OrderApply orderApplyOut = this.getById(outOrderId);
                    //if (orderApplyOut!=null){
                    //}
                    orderApply.setStatus(StatusOrderApplyEnum.TOVOID);
                    orderApply.setAbolishType(2);//作废
                    this.updateById(orderApply);
                    LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId, orderApply.getId()).set(OrderDetail::getStatus, StatusOrderApplyEnum.TOVOID);
                    orderDetailMapper.update(null, orderDetailLambdaUpdateWrapper);

                    orderApplyReturn.setStatus(StatusOrderApplyEnum.TOVOID);
                    orderApplyReturn.setAbolishType(2);//作废
                    this.updateById(orderApplyReturn);
                } else {
                    throw new CommonException(ResultCode.FAIL);
                }
            } else if (orderApply.getOrderType().getKey() == 8) {

                OrderApply orderApplyReturn = orderApplyMapper.getOneForOrderNo(orderApply.getOrderNo(), 4);
                if (orderApplyReturn != null) {
                    //转名额的恢复数据从退费里恢复
                    List<OrderTransferDetail> orderTransferDetailList = iOrderTransferDetailService.list(new QueryWrapper<OrderTransferDetail>().eq("order_id", orderApplyReturn.getId()));
                    Long outOrderId = null;
                    for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
                        outOrderId = orderTransferDetail.getOldOrderId();
                        OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                        orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + orderTransferDetail.getOutHouse());
                        BigDecimal outPrice = orderTransferDetail.getOutPrice();
                        BigDecimal residuePrice = orderDetail.getResiduePrice().add(outPrice);

                        orderDetail.setTurnOutHouse(orderDetail.getTurnOutHouse() - orderTransferDetail.getOutHouse());//恢复转出课时
                        orderDetail.setTurnOutPrice(orderDetail.getTurnOutPrice().subtract(outPrice));

                        orderDetail.setReadingStatus(ReadingStatusEnum.IN_READING);
                        orderDetail.setResiduePrice(residuePrice);
                        iOrderDetailService.updateById(orderDetail);
                        orderTransferDetail.setStatus(2);//设置为作废
                        iOrderTransferDetailService.updateById(orderTransferDetail);
                    }
                    //OrderApply orderApplyOut = this.getById(outOrderId);
                    //if (orderApplyOut!=null){
                    //}
                    orderApply.setStatus(StatusOrderApplyEnum.TOVOID);
                    orderApply.setAbolishType(2);//作废
                    this.updateById(orderApply);
                    LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId, orderApply.getId()).set(OrderDetail::getStatus, StatusOrderApplyEnum.TOVOID);
                    orderDetailMapper.update(null, orderDetailLambdaUpdateWrapper);

                    orderApplyReturn.setStatus(StatusOrderApplyEnum.TOVOID);
                    orderApplyReturn.setAbolishType(2);//作废
                    this.updateById(orderApplyReturn);

                } else {
                    throw new CommonException(ResultCode.FAIL);
                }
            } else if (orderApply.getOrderType().getKey() == 9) {

                OrderApply orderApplyReturn = orderApplyMapper.getOneForOrderNo(orderApply.getOrderNo(), 4);
                if (orderApplyReturn != null) {
                    //转科目的恢复数据从退费里恢复
                    List<OrderTransferDetail> orderTransferDetailList = iOrderTransferDetailService.list(new QueryWrapper<OrderTransferDetail>().eq("order_id", orderApplyReturn.getId()));
                    Long outOrderId = null;
                    for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
                        outOrderId = orderTransferDetail.getOldOrderId();
                        OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                        orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + orderTransferDetail.getOutHouse());
                        BigDecimal outPrice = orderTransferDetail.getOutPrice();
                        BigDecimal residuePrice = orderDetail.getResiduePrice().add(outPrice);

                        orderDetail.setTurnOutHouse(orderDetail.getTurnOutHouse() - orderTransferDetail.getOutHouse());//恢复转出课时
                        orderDetail.setTurnOutPrice(orderDetail.getTurnOutPrice().subtract(outPrice));

                        orderDetail.setReadingStatus(ReadingStatusEnum.IN_READING);
                        orderDetail.setResiduePrice(residuePrice);
                        iOrderDetailService.updateById(orderDetail);
                        orderTransferDetail.setStatus(2);//设置为作废
                        iOrderTransferDetailService.updateById(orderTransferDetail);
                    }
                    //OrderApply orderApplyOut = this.getById(outOrderId);
                    //if (orderApplyOut!=null){
                    //}
                    orderApply.setStatus(StatusOrderApplyEnum.TOVOID);
                    orderApply.setAbolishType(2);//作废
                    this.updateById(orderApply);
                    LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId, orderApply.getId()).set(OrderDetail::getStatus, StatusOrderApplyEnum.TOVOID);
                    orderDetailMapper.update(null, orderDetailLambdaUpdateWrapper);

                    orderApplyReturn.setStatus(StatusOrderApplyEnum.TOVOID);
                    orderApplyReturn.setAbolishType(2);//作废
                    this.updateById(orderApplyReturn);
                } else {
                    throw new CommonException(ResultCode.FAIL);
                }
            }

            QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
            enrollInfoQueryWrapper.eq("order_id", orderApply.getId());
            List<EnrollInfo> enrollInfoList = enrollInfoMapper.selectList(enrollInfoQueryWrapper);
            for (EnrollInfo enrollInfo : enrollInfoList) {
                enrollInfoMapper.deleteById(enrollInfo);
            }

            /**
             * 缴费信息
             */
            QueryWrapper<RatePay> ratePayQueryWrapper = new QueryWrapper<>();
            ratePayQueryWrapper.eq("order_id", id);
            iRatePayService.remove(ratePayQueryWrapper);
            //删除续报成交数据
            QueryWrapper<DealInfo> dealInfoQueryWrapper = new QueryWrapper<>();
            dealInfoQueryWrapper.eq("order_id", id);
            iDealInfoService.remove(dealInfoQueryWrapper);
        }
        return true;
    }

    /**
     * 优惠作废
     *
     * @param disOrderId
     * @param adminId
     * @param isSuper
     * @return
     */
    @Override
    @Transactional
    public boolean invalidateDis(Long disOrderId, Long adminId, Integer isSuper) {

        QueryWrapper<OrderDisPrice> orderDisPriceQueryWrapper = new QueryWrapper<>();
        orderDisPriceQueryWrapper.eq("dis_order_id", disOrderId);
        orderDisPriceQueryWrapper.last("limit 1");
        OrderDisPrice orderDisPrice = iOrderDisPriceService.getOne(orderDisPriceQueryWrapper);

        /*QueryWrapper<OrderDisDetail> orderDisDetailQueryWrapper = new QueryWrapper<>();
        orderDisPriceQueryWrapper.eq("dis_price_id",disOrderId);
        iOrderDisDetailService.remove(orderDisDetailQueryWrapper);*/

        iOrderDisPriceService.delDisPrice(orderDisPrice, 2);

        return true;
    }


    @Override
    @Transactional
    public boolean addDiscount(OrderDetail orderDetail) {

        LocalDate nowDate = LocalDate.now();
        OrderApply orderApply = orderApplyMapper.selectById(orderDetail.getOrderId());
        if (orderApply == null) {
            throw new CommonException(ResultCode.NOORDER);
        }
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();

        orderDetailQueryWrapper.eq("order_id", orderApply.getId());
        orderDetailQueryWrapper.last("limit 1");
        OrderDetail orderDetailInfo = iOrderDetailService.getOne(orderDetailQueryWrapper);
        if (orderDetailInfo == null) {
            throw new CommonException(ResultCode.ORDERDETAIL_NOT);
        }

        //System.out.println("orderDetail.getDiscountsPrice()："+orderDetail.getDiscountsPrice());

        /*BigDecimal discountsPrice = orderDetailInfo.getDiscountsPrice().add(orderDetail.getDiscountsPrice());

        if (orderDetailInfo.getResiduePrice().compareTo(discountsPrice)<0){
            throw new CommonException(ResultCode.DISCOUNTS_PRICE_NOT);
        }*/

        //System.out.println("discountsPrice:"+discountsPrice);

        //System.out.println("orderDetail.getPrice().subtract(discountsPrice):"+orderDetailInfo.getPrice().subtract(discountsPrice));

        BigDecimal diffPrice = orderDetail.getDiscountsPrice().subtract(orderDetailInfo.getDiscountsPrice());

        /**
         * 实际优惠
         */
        //BigDecimal solidDisPrice = orderDetailInfo.getDiscountsPrice().add(diffPrice);

        if (diffPrice.compareTo(orderDetailInfo.getResiduePrice()) > 0) {
            throw new CommonException(ResultCode.DISCOUNTS_PRICE_NOT);
        }

        orderDetailInfo.setDiscountsPrice(orderDetail.getDiscountsPrice());//优惠金额
        orderDetailInfo.setDiscountsDate(nowDate);
        orderDetailInfo.setSolidPrice(orderDetailInfo.getPrice().subtract(orderDetail.getDiscountsPrice()));//实收金额
        orderDetailInfo.setResiduePrice(orderDetailInfo.getResiduePrice().subtract(diffPrice));//剩余金额
        iOrderDetailService.updateById(orderDetailInfo);

        orderApply.setDiscountsDate(orderApply.getHandleDate());
        //orderApply.setPrice(orderApply.getPrice().subtract(orderDetail.getDiscountsPrice()));
        orderApply.setDisPrice(orderDetail.getDiscountsPrice());//优惠金额
        if (orderApply.getIsOwn().equals(0)) {
            orderApply.setSolidPrice(orderApply.getPrice().subtract(orderDetail.getDiscountsPrice()));
        } else if (orderApply.getIsOwn().equals(1) && orderApply.getOwnPrice().compareTo(orderDetail.getDiscountsPrice()) >= 0) {
            orderApply.setOwnPrice(orderApply.getOwnPrice().subtract(orderDetail.getDiscountsPrice()));
        }

        orderApplyMapper.updateById(orderApply);

        return true;
    }

    @Override
    @Transactional
    public boolean orderHouseChange(Long orderId, Integer diffCount) {
        OrderApply orderApply = orderApplyMapper.selectById(orderId);
        if (orderApply == null) {
            return false;
        }

        Integer diffNum = diffCount * 3;

        BigDecimal diffPrice = new BigDecimal(0);

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();

        orderDetailQueryWrapper.eq("order_id", orderId);

        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);
        boolean rs = true;
        for (OrderDetail orderDetail : orderDetailList) {
            CoursePricing coursePricing = iCoursePricingService.getById(orderDetail.getCoursePriceId());
            if (coursePricing == null) {
                rs = false;
                break;
            }
            diffPrice = diffPrice.add(coursePricing.getUnitPrice().multiply(new BigDecimal(diffCount)));

            orderDetail.setAllCourseCount(orderDetail.getAllCourseCount() + diffNum);//总课时
            orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + diffNum);//剩余课时
            orderDetail.setPrice(orderDetail.getPrice().add(diffPrice));//应收金额
            orderDetail.setSolidPrice(orderDetail.getSolidPrice().add(diffPrice));//实收金额
            orderDetail.setResiduePrice(orderDetail.getResiduePrice().add(diffPrice));
            iOrderDetailService.updateById(orderDetail);
        }
        if (orderApply.getPrice().compareTo(BigDecimal.ZERO) > 0) {
            orderApply.setPrice(orderApply.getPrice().add(diffPrice));
        }
        if (orderApply.getSolidPrice().compareTo(BigDecimal.ZERO) > 0) {
            orderApply.setSolidPrice(orderApply.getSolidPrice().add(diffPrice));
        }

        orderApplyMapper.updateById(orderApply);
        return true;
    }

    /**
     * 两期内是否有报名
     *
     * @param subjectsId
     * @param studentId
     * @return
     */
    public Long getApplyCount(String subjectsId, String studentId) {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        Long quarterIdStart = quarterNow.getId() - 2L;
        Long quarterIdEnd = quarterNow.getId();


        Student student = iStudentService.getById(studentId);

        Long count = 0L;// 0为算招生信息
        String moreStudent = "0";//是否通过姓名查询多个学员,0否，1是
        if (!StringUtils.isNotBlank(student.getIdCardNo())) {
            moreStudent = "1";
        }
        /*QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("subjects_id", subjectsId);
        orderDetailQueryWrapper.inSql("student_id", "select id from student where name = '" + student.getName() + "'");
        orderDetailQueryWrapper.eq("deleted", 0);
        orderDetailQueryWrapper.eq("lesson_type", 1);
        orderDetailQueryWrapper.ne("status", 2);
        orderDetailQueryWrapper.ne("order_type", 4);
        count = iOrderDetailService.count(orderDetailQueryWrapper);*/
        count = orderDetailMapper.getStudentApplyCount(studentId, student.getName(), subjectsId, "1", quarterIdStart.toString(), quarterIdEnd.toString(), moreStudent);

        //调整后
        // 1、所报读科目两期内没有报读，并且其它科目两期内没有报读，算有招生数据
        // 2、所报读科目两期内没有报读，并且其它科目两期内有报读并且所报读的科目剩余课时都要大于15课次，算有招生数
        if (count == null || count.equals(0L)) {
            // 判断其他科目两期内是否有报读，没有报读的话算招生信息
            List<Long> readdSubjectsList = orderDetailMapper.getStudentApplyCount2(studentId, student.getName(), subjectsId, "1", quarterIdStart.toString(), quarterIdEnd.toString(), moreStudent);
            for (Long readdSubjects : readdSubjectsList) {
                // 其他科目两期内有报读信息，判断所报读的科目剩余课时是否大于15课次
                Long isResidueGreat = orderDetailMapper.getStudentApplyCount3(studentId, student.getName(), readdSubjects.toString(), "1", quarterIdStart.toString(), quarterIdEnd.toString(), moreStudent);
                //其它科目，不大于15课次，不算有招生数据
                if (isResidueGreat == 0) {
                    // 所报读的科目剩余课时不大于15课次，不算招生信息
                    count = 1L;
                }
            }
        }

        count = count == null ? 0 : count;
        return count;//0算有招生数据，1不算有招生数据
    }

    /**
     * 判断是否为新生使用
     *
     * @param subjectsId
     * @param studentId
     * @return
     */
    @Override
    public Long getApplyCountForIsNew(String subjectsId, String studentId) {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        Long quarterIdStart = quarterNow.getId() - 2L;
        Long quarterIdEnd = quarterNow.getId();


        Student student = iStudentService.getById(studentId);

        Long count = 0L;// 0为算招生信息
        String moreStudent = "0";//是否通过姓名查询多个学员,0否，1是
        if (!StringUtils.isNotBlank(student.getIdCardNo())) {
            moreStudent = "1";
        }
        count = orderDetailMapper.getStudentApplyCount(studentId, student.getName(), subjectsId, "1", quarterIdStart.toString(), quarterIdEnd.toString(), moreStudent);
        count = count == null ? 0 : count;
        return count;
    }


    /**
     * 因为保存时，已经添加了保存的数据，所以要-1
     *
     * @param subjectsId
     * @param studentId
     * @return
     */
    public Long getApplyCountAdd(String subjectsId, String studentId) {
        Student student = iStudentService.getById(studentId);
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("subjects_id", subjectsId);
        orderDetailQueryWrapper.inSql("student_id", "select id from student where name = '" + student.getName() + "'");
        orderDetailQueryWrapper.eq("deleted", 0);
        orderDetailQueryWrapper.eq("lesson_type", 1);
        orderDetailQueryWrapper.ne("status", 2);
        orderDetailQueryWrapper.ne("order_type", 4);
        Long count = iOrderDetailService.count(orderDetailQueryWrapper);
        return count;
    }

    /**
     * 异常金额处理
     *
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @param orderDetailId
     * @param newOutPrice
     * @return
     */
    public boolean abnormalPriceDispose(Integer yearPart, Integer quarterNum, Long schoolId, Long studentId, Long subjectsId, Long orderDetailId, BigDecimal newOutPrice) {
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("year_part", yearPart);
        recordCourseQueryWrapper.eq("quarter", quarterNum);
        recordCourseQueryWrapper.eq("school_id", schoolId);
        recordCourseQueryWrapper.eq("student_id", studentId);
        recordCourseQueryWrapper.eq("subjects_id", subjectsId);
        recordCourseQueryWrapper.eq("is_deduct_house", 1);
        recordCourseQueryWrapper.eq("is_deduct_money", 1);
        recordCourseQueryWrapper.orderByDesc("created_at");
        recordCourseQueryWrapper.last("limit 1");
        RecordCourse recordCourse = iRecordCourseService.getOne(recordCourseQueryWrapper);
        //如果有上课记录，直接添加到上课记录里
        if (recordCourse != null) {
            recordCourse.setBuckleClassMoney(recordCourse.getBuckleClassMoney().add(newOutPrice));
            iRecordCourseService.updateById(recordCourse);
            RecordCost recordCost = iRecordCostService.getOne(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourse.getId()));
            if (recordCost != null) {
                recordCost.setBuckleClassMoney(recordCost.getBuckleClassMoney().add(newOutPrice));
                iRecordCostService.updateById(recordCost);
            }
        } else {
            //如没有上课记录，直接添加到订单的异常里面
            OrderDetail orderDetailOld = iOrderDetailService.getById(orderDetailId);
            if (orderDetailOld.getResidueCourseCount() > 0) {
                orderDetailOld.setResiduePrice(orderDetailOld.getResiduePrice().add(newOutPrice));
            } else {
                orderDetailOld.setAbnormalPrice(orderDetailOld.getAbnormalPrice().add(newOutPrice));
            }

            iOrderDetailService.updateById(orderDetailOld);
        }
        return true;
    }

    @Override
    public IPage<ReturnPremiumDailySheet> getReturnPremiumDailySheet(IPage<?> page, String orderType, String startDate, String endDate, String schoolIdList, String subjectsId, String yearClassId, String isPrint, String studentName, String status, String teacherId) {
        return orderApplyMapper.getReturnPremiumDailySheet(page, orderType, startDate, endDate, schoolIdList, subjectsId, yearClassId, isPrint, studentName, status, teacherId);
    }

    @Override
    public BigDecimal getReturnPremiumPrice(String orderType, String startDate, String endDate, String schoolIdList, String subjectsId, String yearClassId, String isPrint, String studentName, String status, String teacherId) {
        return orderApplyMapper.getReturnPremiumPrice(orderType, startDate, endDate, schoolIdList, subjectsId, yearClassId, isPrint, studentName, status, teacherId);
    }

    @Override
    @Transactional
    public boolean addOrderDisDetaill(List<Long> studentList, Long orderId, List<OrderDisDetail> orderDisDetailList, BigDecimal disPrice, LocalDate discountsDate, Long createdId) {
        if (discountsDate == null) {
            discountsDate = LocalDate.now();
        }
        OrderApply orderApplyInfo = this.getById(orderId);
        if (orderApplyInfo == null) {
            throw new CommonException(ResultCode.ORDERDETAIL_NOT);
        }

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("order_id", orderId);
        orderDetailQueryWrapper.orderByAsc("id");
        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);
        //BigDecimal allDisPrice = disPrice;

        Integer yearClassId = null;
        Set<String> subjectsIdSet = new HashSet<>();
        Integer i = 0;
        Long orderDetailId = 0L;
        for (OrderDetail orderDetail : orderDetailList) {
            if (i > 0) {
                continue;
            }
            BigDecimal allDisPrice = orderDetail.getDiscountsPrice().add(disPrice);
            orderDetail.setDiscountsPrice(allDisPrice);
            orderDetail.setDiscountsDate(discountsDate);
            BigDecimal residuePrice = orderDetail.getResiduePrice().subtract(disPrice);
            orderDetail.setResiduePrice(residuePrice);
            BigDecimal solidPrice = orderDetail.getSolidPrice().subtract(disPrice);
            orderDetail.setSolidPrice(solidPrice);
            iOrderDetailService.updateById(orderDetail);
            yearClassId = orderDetail.getYearClassId();
            subjectsIdSet.add(orderDetail.getSubjectsId().toString());

            orderDetailId = orderDetail.getId();
        }
        int[] randMath = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
        Integer randReceiptNo = CommonUtil.getNotSimple(randMath, 7);
        OrderApply orderApplyDis = new OrderApply();
        //BeanUtils.copyProperties(orderApplyInfo,orderApplyDis);
        orderApplyDis.setId(idWorker.nextId());
        orderApplyDis.setReceiptNo(randReceiptNo.toString());
        orderApplyDis.setPrice(BigDecimal.ZERO);
        orderApplyDis.setSolidPrice(BigDecimal.ZERO);
        orderApplyDis.setOwnPrice(BigDecimal.ZERO);
        orderApplyDis.setDisPrice(disPrice);
        orderApplyDis.setCostType(1);
        orderApplyDis.setOrderType(OrderTypeEnum.ORDER_TYPE_DIS);
        orderApplyDis.setLessonType(orderApplyInfo.getLessonType());
        orderApplyDis.setDiscountsDate(discountsDate);
        orderApplyDis.setYearPart(orderApplyInfo.getYearPart());
        orderApplyDis.setQuarterNum(orderApplyInfo.getQuarterNum());
        orderApplyDis.setStudentId(orderApplyInfo.getStudentId());
        orderApplyDis.setSchoolId(orderApplyInfo.getSchoolId());
        orderApplyDis.setHandleSchoolId(orderApplyInfo.getHandleSchoolId());
        orderApplyDis.setHandleSchoolName(orderApplyInfo.getHandleSchoolName());
        orderApplyDis.setHandlePersonId(createdId);
        Staff staff = iStaffService.getOneById(createdId);
        orderApplyDis.setHandlePersonName(staff.getName());
        orderApplyDis.setTradeContent(orderApplyInfo.getTradeContent());
        orderApplyDis.setHandleDate(discountsDate);
        orderApplyDis.setYearClassId(yearClassId);
        if (subjectsIdSet.size() > 0) {
            orderApplyDis.setSubjectsIdStr(String.join(",", subjectsIdSet));
        }

        this.save(orderApplyDis);


        //BigDecimal allDisPriceApply = orderApplyInfo.getDisPrice().add(disPrice);
        //orderApplyInfo.setDisPrice(allDisPriceApply);
        //orderApplyInfo.setSolidPrice(orderApplyInfo.getSolidPrice().subtract(disPrice));
        //this.updateById(orderApplyInfo);
//        iOrderDisDetailService.addDisDetaill(orderId,orderApplyDis.getId(),orderDisDetailList,disPrice,discountsDate);

        // 直系亲属保存
        iOrderDisDetailService.addDisDetailAndClan(studentList, orderDetailId, orderId, orderApplyDis.getId(), orderDisDetailList, disPrice, discountsDate);


        //orderApplyDis.setApplyType(OrderTypeEnum.ORDER_TYPE_DIS);

        return true;
    }

    @Override
    public Integer getNotAffirmCount(Integer yearPart,
                                     Integer quarterNum,
                                     Long schoolId,
                                     Long studentId,
                                     String subjectsId
    ) {
        return orderApplyMapper.getNotAffirmCount(yearPart, quarterNum, schoolId, studentId, subjectsId);
    }

    @Override
    public String getNotAffirmStudentName(Integer yearPart,
                                          Integer quarterNum,
                                          Long schoolId,
                                          String studentId,
                                          String subjectsId) {
        return orderApplyMapper.getNotAffirmStudentName(yearPart, quarterNum, schoolId, studentId, subjectsId);
    }

    @Override
    public String getNotAffirmStudentNameForGradeId(Integer yearPart,
                                                    Integer quarterNum,
                                                    Long schoolId,
                                                    String subjectsId,
                                                    Long gradeId) {
        return orderApplyMapper.getNotAffirmStudentNameForGradeId(yearPart, quarterNum, schoolId, subjectsId, gradeId);
    }

    @Override
    public OrderApply getOrderApplySum(Wrapper wrapper) {
        return orderApplyMapper.getOrderApplySum(wrapper);
    }
}
